Vehicles dictionary updater

This commit is contained in:
Mikhail Shabanov committed 2020-06-07 14:39:03 +02:00
1 parent 6a9b69b254
commit 4a11ed61df
11 files changed
+525 -4

No files matched your search

@@ -0,0 +1,18 @@
namespace WotBlitzStatisticsPro.Common.Dictionaries
{
/// <summary>
/// Price of vehicle
/// </summary>
public class VehiclePriceInXp
{
///<summary>
/// VehicleId
///</summary>
public long TankId { get; set; }
/// <summary>
/// Vehicle price in XP
/// </summary>
public long PricesXp { get; set; }
}
}
@@ -0,0 +1,96 @@
using System.Collections.Generic;
namespace WotBlitzStatisticsPro.Common.Dictionaries
{
/// <summary>
/// Vehicle dictionary item
/// </summary>
public class VehiclesDictionary
{
///<summary>
/// VehicleId
///</summary>
public long TankId { get; set; }
///<summary>
/// Vehicle name
///</summary>
public List<LocalizableString> Name { get; set; }
///<summary>
/// Vehicle description
///</summary>
public List<LocalizableString> Description { get; set; }
///<summary>
/// Is vehicle premium
///</summary>
public bool IsPremium { get; set; }
///<summary>
/// Vehicle type id
///</summary>
public string TypeId { get; set; }
///<summary>
/// Vehicle nationId
///</summary>
public string NationId { get; set; }
///<summary>
/// Vehicle tier
///</summary>
public int Tier { get; set; }
/// <summary>
/// Vehicle preview image
/// </summary>
public string PreviewImage { get; set; }
/// <summary>
/// Vehicle normal image
/// </summary>
public string NormalImage { get; set; }
/// <summary>
/// Vehicle price in credits
/// </summary>
public decimal PriceCredit { get; set; }
/// <summary>
/// Vehicle price in gold
/// </summary>
public decimal PriceGold { get; set; }
/// <summary>
/// Ids of nex tanks and their cost in XP
/// </summary>
public List<VehiclePriceInXp> NexTanksInTree { get; set; }
///<summary>
/// Price in XP for parent vehicle as key
///</summary>
public List<VehiclePriceInXp> PriceXp { get; set; }
///<summary>
/// Engines id list
///</summary>
public int[] Engines { get; set; }
///<summary>
/// Guns id list
///</summary>
public int[] Guns { get; set; }
///<summary>
/// List of compatible suspensions
///</summary>
public int[] Suspensions { get; set; }
///<summary>
/// List of compatible turrets ids
///</summary>
public int[] Turrets { get; set; }
}
}
@@ -14,6 +14,7 @@ namespace WotBlitzStatisticsPro.DataAccess
private const string ClanRolesCollectionName = "dictionary-clan-roles";
private const string AchievementsSectionsCollectionName = "dictionary-achievements-sections";
private const string AchievementsCollectionName = "dictionary-achievements";
private const string VehiclesCollectionName = "dictionary-vehicles";
private readonly IMongoDatabase _database;
@@ -72,5 +73,14 @@ namespace WotBlitzStatisticsPro.DataAccess
await dbAchievementSections.DeleteManyAsync(Builders<AchievementDictionary>.Filter.Empty);
await dbAchievementSections.InsertManyAsync(achievementDictionary);
}
public async Task UpdateVehicles(List<VehiclesDictionary> vehiclesDictionary)
{
var dbVehicles =
_database.GetCollection<VehiclesDictionary>(VehiclesCollectionName);
await dbVehicles.DeleteManyAsync(Builders<VehiclesDictionary>.Filter.Empty);
await dbVehicles.InsertManyAsync(vehiclesDictionary);
}
}
}
@@ -17,5 +17,7 @@ namespace WotBlitzStatisticsPro.DataAccess
Task UpdateAchievementsSections(List<AchievementSectionDictionary> achievementSections);
Task UpdateAchievements(List<AchievementDictionary> achievementDictionary);
Task UpdateVehicles(List<VehiclesDictionary> vehiclesDictionary);
}
}
@@ -1,9 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using WotBlitzStatisticsPro.Common.Dictionaries;
using WotBlitzStatisticsPro.Common.Model;
using WotBlitzStatisticsPro.DataAccess;
using WotBlitzStatisticsPro.WgApiClient;
using WotBlitzStatisticsPro.WgApiClient.Model;
namespace WotBlitzStatisticsPro.Logic.Dictionaries
{
@@ -16,19 +20,58 @@ namespace WotBlitzStatisticsPro.Logic.Dictionaries
[Obsolete("Parameter-less constructor only for unit tests")]
public VehiclesDictionaryUpdater()
{
}
public VehiclesDictionaryUpdater(IWargamingDictionariesApiClient wargamingDictionariesApiClient, IDictionariesDataAccessor dataAccessor, IMapper mapper)
public VehiclesDictionaryUpdater(IWargamingDictionariesApiClient wargamingDictionariesApiClient,
IDictionariesDataAccessor dataAccessor, IMapper mapper)
{
_wargamingDictionariesApiClient = wargamingDictionariesApiClient;
_dataAccessor = dataAccessor;
_mapper = mapper;
}
public virtual Task<UpdateDictionariesResponseItem> Update()
public virtual async Task<UpdateDictionariesResponseItem> Update()
{
throw new System.NotImplementedException();
var vehiclesDictionary = await GetAndMapVehiclesDictionary();
await _dataAccessor.UpdateVehicles(vehiclesDictionary);
return new UpdateDictionariesResponseItem
{
DictionaryType = DictionaryType.Vehicles,
Description = $"Got and saved {vehiclesDictionary.Count} vehicles dictionary items"
};
}
private async Task<List<VehiclesDictionary>> GetAndMapVehiclesDictionary()
{
var defaultRealmType = RealmType.Eu;
var vehicles = new List<VehiclesDictionary>();
foreach (var requestLanguage in (RequestLanguage[]) Enum.GetValues(typeof(RequestLanguage)))
{
var wgVehicles =
await _wargamingDictionariesApiClient.GetVehicles(defaultRealmType, requestLanguage);
foreach (var wgVehicle in wgVehicles)
{
var mappedVehicle = vehicles.FirstOrDefault(v => v.TankId == wgVehicle.TankId);
if (mappedVehicle == null)
{
mappedVehicle = _mapper.Map<WotEncyclopediaVehiclesResponse, VehiclesDictionary>(wgVehicle);
vehicles.Add(mappedVehicle);
}
mappedVehicle.Name.Add(new LocalizableString {Language = requestLanguage, Value = wgVehicle.Name});
mappedVehicle.Description.Add(new LocalizableString {Language = requestLanguage, Value = wgVehicle.Description});
}
}
return vehicles;
}
}
}
@@ -0,0 +1,39 @@
using System.Collections.Generic;
using AutoMapper;
using WotBlitzStatisticsPro.Common.Dictionaries;
using WotBlitzStatisticsPro.WgApiClient.Model;
namespace WotBlitzStatisticsPro.Logic.Mappers
{
public class VehicleDictionaryProfile : Profile
{
public VehicleDictionaryProfile()
{
CreateMap<WotEncyclopediaVehiclesResponse, VehiclesDictionary>()
.ForMember(d => d.TankId,
o => o.MapFrom(s => s.TankId))
.ForMember(d => d.Name, o => o.MapFrom(_ => new List<LocalizableString>()))
.ForMember(d => d.Description, o => o.MapFrom(_ => new List<LocalizableString>()))
.ForMember(d => d.TypeId,
o => o.MapFrom(s => s.Type))
.ForMember(d => d.NationId,
o => o.MapFrom(s => s.Nation))
.ForMember(d => d.Tier,
o => o.MapFrom(s => s.Tier))
.ForMember(d => d.PreviewImage,
o => o.MapFrom(s => s.Images["preview"]))
.ForMember(d => d.NormalImage,
o => o.MapFrom(s => s.Images["normal"]))
.ForMember(d => d.PriceCredit,
o => o.MapFrom(s => s.Cost["price_credit"]))
.ForMember(d => d.PriceGold,
o => o.MapFrom(s => s.Cost["price_gold"]))
.ForMember(d => d.NexTanksInTree,
o =>
o.MapFrom(s => s.NextTanks))
.ForMember(d => d.PriceXp,
o =>
o.MapFrom(s => s.PricesXp));
}
}
}
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using AutoMapper;
using WotBlitzStatisticsPro.Common.Dictionaries;
namespace WotBlitzStatisticsPro.Logic.Mappers
{
public class VehiclePriceProfile : Profile
{
public VehiclePriceProfile()
{
CreateMap<KeyValuePair<string, string>, VehiclePriceInXp>()
.ForMember(d => d.TankId,
o => o.MapFrom(s => Convert.ToInt64(s.Key)))
.ForMember(d => d.PricesXp,
o => o.MapFrom(s => Convert.ToInt64(s.Value)));
}
}
}
@@ -0,0 +1,163 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.Configuration;
using Bogus;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using WotBlitzStatisticsPro.Common.Dictionaries;
using WotBlitzStatisticsPro.Common.Model;
using WotBlitzStatisticsPro.DataAccess;
using WotBlitzStatisticsPro.Logic.Dictionaries;
using WotBlitzStatisticsPro.Logic.Mappers;
using WotBlitzStatisticsPro.WgApiClient;
using WotBlitzStatisticsPro.WgApiClient.Model;
namespace WotBlitzStatisticsPro.Tests.DictionariesTests
{
[TestFixture]
public class VehiclesDictionaryUpdaterTests
{
private VehiclesDictionaryUpdater _vehiclesDictionariesUpdater;
private Mock<IWargamingDictionariesApiClient> _wargamingDictionariesApiClientMock;
private Mock<IDictionariesDataAccessor> _dataAccessorMock;
private List<WotEncyclopediaVehiclesResponse> _vehiclesInfoResponseEn;
private List<WotEncyclopediaVehiclesResponse> _vehiclesInfoResponseRu;
private List<WotEncyclopediaVehiclesResponse> _vehiclesInfoResponseDe;
[SetUp]
public void Init()
{
// Generating fake data
_vehiclesInfoResponseEn = GetVehiclesInfoResponse("en");
_vehiclesInfoResponseRu = GetVehiclesInfoResponse("ru", _vehiclesInfoResponseEn);
_vehiclesInfoResponseDe = GetVehiclesInfoResponse("de", _vehiclesInfoResponseEn);
// Real mapper instance
var configurationExp = new MapperConfigurationExpression();
configurationExp.AddProfile<VehiclePriceProfile>();
configurationExp.AddProfile<VehicleDictionaryProfile>();
var mapperConfiguration = new MapperConfiguration(configurationExp);
IMapper mapper = new Mapper(mapperConfiguration);
// Wargaming client mock
_wargamingDictionariesApiClientMock = new Mock<IWargamingDictionariesApiClient>();
_wargamingDictionariesApiClientMock.Setup(w =>
w.GetVehicles(It.IsAny<RealmType>(), RequestLanguage.En))
.ReturnsAsync(_vehiclesInfoResponseEn);
_wargamingDictionariesApiClientMock.Setup(w =>
w.GetVehicles(It.IsAny<RealmType>(), RequestLanguage.Ru))
.ReturnsAsync(_vehiclesInfoResponseRu);
_wargamingDictionariesApiClientMock.Setup(w =>
w.GetVehicles(It.IsAny<RealmType>(), RequestLanguage.De))
.ReturnsAsync(_vehiclesInfoResponseDe);
// MongoDb data accessor mock
_dataAccessorMock = new Mock<IDictionariesDataAccessor>();
_vehiclesDictionariesUpdater = new VehiclesDictionaryUpdater(
_wargamingDictionariesApiClientMock.Object,
_dataAccessorMock.Object,
mapper);
}
[Test]
public async Task ShouldCallWargamingApi3Times()
{
await _vehiclesDictionariesUpdater.Update();
// Should call wargaming API once for each language
_wargamingDictionariesApiClientMock.Verify(d => d.GetVehicles(It.IsAny<RealmType>(), RequestLanguage.En), Times.Once);
_wargamingDictionariesApiClientMock.Verify(d => d.GetVehicles(It.IsAny<RealmType>(), RequestLanguage.Ru), Times.Once);
_wargamingDictionariesApiClientMock.Verify(d => d.GetVehicles(It.IsAny<RealmType>(), RequestLanguage.De), Times.Once);
}
[Test]
public async Task ShouldSaveAppropriateVehiclesDictionary()
{
List<VehiclesDictionary> targetVehicleDictionary = null;
_dataAccessorMock
.Setup(d => d.UpdateVehicles(It.IsAny<List<VehiclesDictionary>>()))
.Callback((List<VehiclesDictionary> dictionary) => targetVehicleDictionary = dictionary);
await _vehiclesDictionariesUpdater.Update();
targetVehicleDictionary.Should().NotBeNull();
targetVehicleDictionary.Should().HaveCount(targetVehicleDictionary.Count);
for (var i = 0; i < targetVehicleDictionary.Count; i++)
{
targetVehicleDictionary[i].TankId.Should()
.Be(_vehiclesInfoResponseEn[i].TankId);
targetVehicleDictionary[i].Name.First(n => n.Language == RequestLanguage.En).Value.Should()
.Be(_vehiclesInfoResponseEn[i].Name);
targetVehicleDictionary[i].Name.First(n => n.Language == RequestLanguage.Ru).Value.Should()
.Be(_vehiclesInfoResponseRu[i].Name);
targetVehicleDictionary[i].Name.First(n => n.Language == RequestLanguage.De).Value.Should()
.Be(_vehiclesInfoResponseDe[i].Name);
targetVehicleDictionary[i].Description.First(n => n.Language == RequestLanguage.En).Value.Should()
.Be(_vehiclesInfoResponseEn[i].Description);
targetVehicleDictionary[i].Description.First(n => n.Language == RequestLanguage.Ru).Value.Should()
.Be(_vehiclesInfoResponseRu[i].Description);
targetVehicleDictionary[i].Description.First(n => n.Language == RequestLanguage.De).Value.Should()
.Be(_vehiclesInfoResponseDe[i].Description);
}
}
#region Fixtures
private static List<WotEncyclopediaVehiclesResponse> GetVehiclesInfoResponse(string language, List<WotEncyclopediaVehiclesResponse> baseEncyclopedia = null)
{
var result = new List<WotEncyclopediaVehiclesResponse>();
var faker = new Faker(language);
if (baseEncyclopedia == null)
{
var random = faker.Random;
for (int i = 0; i < random.Number(400); i++)
{
result.Add(FakeNewDictionaryItem(faker));
}
}
else
{
foreach (var achievementsResponse in baseEncyclopedia)
{
result.Add(FakeDictionaryItem(faker, achievementsResponse));
}
}
return result;
}
private static WotEncyclopediaVehiclesResponse FakeNewDictionaryItem(Faker faker)
{
return new WotEncyclopediaVehiclesResponse
{
Name = faker.Commerce.ProductName(),
TankId = faker.Random.Number(9999),
Description = faker.Lorem.Sentence(),
};
}
private static WotEncyclopediaVehiclesResponse FakeDictionaryItem(Faker faker, WotEncyclopediaVehiclesResponse baseResponse)
{
return new WotEncyclopediaVehiclesResponse
{
Name = faker.Commerce.ProductName(),
Description = faker.Lorem.Sentence(),
TankId = baseResponse.TankId
};
}
#endregion
}
}
@@ -16,5 +16,9 @@ namespace WotBlitzStatisticsPro.WgApiClient
Task<List<WotEncyclopediaAchievementsResponse>> GetAchievementsDictionary(
RealmType realmType = RealmType.Ru,
RequestLanguage language = RequestLanguage.En);
Task<List<WotEncyclopediaVehiclesResponse>> GetVehicles(
RealmType realmType = RealmType.Ru,
RequestLanguage language = RequestLanguage.En);
}
}
@@ -0,0 +1,117 @@
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WotBlitzStatisticsPro.WgApiClient.Model
{
public class WotEncyclopediaVehiclesResponse
{
///<summary>
/// Vehicle description
///</summary>
[JsonProperty("description")]
public string Description { get; set; }
///<summary>
/// Engines id list
///</summary>
[JsonProperty("engines")]
public int[] Engines { get; set; }
///<summary>
/// Guns id list
///</summary>
[JsonProperty("guns")]
public int[] Guns { get; set; }
///<summary>
/// Is vehicle premium
///</summary>
[JsonProperty("is_premium")]
public bool IsPremium { get; set; }
///<summary>
/// Vehicle name
///</summary>
[JsonProperty("name")]
public string Name { get; set; }
///<summary>
/// Vehicle nationId
///</summary>
[JsonProperty("nation")]
public string Nation { get; set; }
///<summary>
/// List of next vehicles in tree:
///
/// key - vehicle id,
/// value - amount of XP to open it
///</summary>
[JsonProperty("next_tanks")]
public Dictionary<string, string> NextTanks { get; set; }
///<summary>
/// Vehicle cost by pairs
/// with keys: price_credit, price_gold
///</summary>
[JsonProperty("cost")]
public Dictionary<string, string> Cost { get; set; }
///<summary>
/// Price in XP for parent vehicle as key
///</summary>
[JsonProperty("prices_xp")]
public Dictionary<string, string> PricesXp { get; set; }
///<summary>
/// List of compatible suspensions
///</summary>
[JsonProperty("suspensions")]
public int[] Suspensions { get; set; }
///<summary>
/// VehicleId
///</summary>
[JsonProperty("tank_id")]
public long? TankId { get; set; }
///<summary>
/// Vehicle tier
///</summary>
[JsonProperty("tier")]
public long? Tier { get; set; }
///<summary>
/// List of compatible turrets ids
///</summary>
[JsonProperty("turrets")]
public int[] Turrets { get; set; }
///<summary>
/// Vehicle type id
///</summary>
[JsonProperty("type")]
public string Type { get; set; }
/////<summary>
///// Default vehicle profile
/////</summary>
//[JsonProperty("default_profile")]
//public WotEncyclopediaVehiclesDefaultProfile DefaultProfile { get; set; }
///<summary>
/// List of vehicle images.
/// Keys: preview, normal
///</summary>
[JsonProperty("images")]
public Dictionary<string, string> Images { get; set; }
/////<summary>
///// Information about investigated modules
/////</summary>
//[JsonProperty("modules_tree")]
//public WotEncyclopediaVehiclesModulesTree ModulesTree { get; set; }
}
}
@@ -76,6 +76,16 @@ namespace WotBlitzStatisticsPro.WgApiClient
return response.Values.ToList();
}
public async Task<List<WotEncyclopediaVehiclesResponse>> GetVehicles(RealmType realmType = RealmType.Ru, RequestLanguage language = RequestLanguage.En)
{
var response = await GetFromBlitzApi<Dictionary<string, WotEncyclopediaVehiclesResponse>>(
realmType,
language,
"encyclopedia/vehicles/").ConfigureAwait(false);
return response.Values.ToList();
}
#endregion