[issue #139] client lookup and stats api

This commit is contained in:
RaidMax 2020-05-24 21:22:26 -05:00
parent 4457ee5461
commit 30f2f7bf09
32 changed files with 907 additions and 36 deletions

View File

@ -69,12 +69,12 @@ namespace IW4MAdmin.Application
ITranslationLookup translationLookup, IConfigurationHandler<CommandConfiguration> commandConfiguration, ITranslationLookup translationLookup, IConfigurationHandler<CommandConfiguration> commandConfiguration,
IConfigurationHandler<ApplicationConfiguration> appConfigHandler, IGameServerInstanceFactory serverInstanceFactory, IConfigurationHandler<ApplicationConfiguration> appConfigHandler, IGameServerInstanceFactory serverInstanceFactory,
IEnumerable<IPlugin> plugins, IParserRegexFactory parserRegexFactory, IEnumerable<IRegisterEvent> customParserEvents, IEnumerable<IPlugin> plugins, IParserRegexFactory parserRegexFactory, IEnumerable<IRegisterEvent> customParserEvents,
IEventHandler eventHandler, IScriptCommandFactory scriptCommandFactory) IEventHandler eventHandler, IScriptCommandFactory scriptCommandFactory, IDatabaseContextFactory contextFactory)
{ {
MiddlewareActionHandler = actionHandler; MiddlewareActionHandler = actionHandler;
_servers = new ConcurrentBag<Server>(); _servers = new ConcurrentBag<Server>();
MessageTokens = new List<MessageToken>(); MessageTokens = new List<MessageToken>();
ClientSvc = new ClientService(); ClientSvc = new ClientService(contextFactory);
AliasSvc = new AliasService(); AliasSvc = new AliasService();
PenaltySvc = new PenaltyService(); PenaltySvc = new PenaltyService();
ConfigHandler = appConfigHandler; ConfigHandler = appConfigHandler;

View File

@ -10,7 +10,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" /> <PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" />
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.11" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -10,7 +10,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.11" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -16,7 +16,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.11" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -23,7 +23,7 @@
</Target> </Target>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.11" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -16,7 +16,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.11" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -0,0 +1,10 @@
namespace Stats.Dtos
{
public class StatsInfoRequest
{
/// <summary>
/// client identifier
/// </summary>
public int? ClientId { get; set; }
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Text.Json.Serialization;
namespace Stats.Dtos
{
public class StatsInfoResult
{
/// <summary>
/// ranking on the server
/// </summary>
public int Ranking { get; set; }
/// <summary>
/// number of kills
/// </summary>
public int Kills { get; set; }
/// <summary>
/// number of deaths
/// </summary>
public int Deaths { get; set; }
/// <summary>
/// performance level (elo rating + skill) / 2
/// </summary>
public double Performance { get; set; }
/// <summary>
/// SPM
/// </summary>
public double ScorePerMinute { get; set; }
/// <summary>
/// last connection
/// </summary>
public DateTime LastPlayed { get; set; }
/// <summary>
/// how many seconds played on the server
/// </summary>
public double TotalSecondsPlayed { get; set; }
/// <summary>
/// name of the server
/// </summary>
public string ServerName { get; set; }
/// <summary>
/// server game
/// </summary>
public string ServerGame { get; set; }
[JsonIgnore]
public long ServerId { get; set; }
}
}

View File

@ -0,0 +1,75 @@
using IW4MAdmin.Plugins.Stats.Models;
using Microsoft.EntityFrameworkCore;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using Stats.Dtos;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Stats.Helpers
{
/// <summary>
/// implementation for IResourceQueryHelper
/// used to obtain client statistics information
/// </summary>
public class StatsResourceQueryHelper : IResourceQueryHelper<StatsInfoRequest, StatsInfoResult>
{
private readonly IDatabaseContextFactory _contextFactory;
public StatsResourceQueryHelper(IDatabaseContextFactory databaseContextFactory)
{
_contextFactory = databaseContextFactory;
}
/// <inheritdoc/>
public async Task<ResourceQueryHelperResult<StatsInfoResult>> QueryResource(StatsInfoRequest query)
{
var result = new ResourceQueryHelperResult<StatsInfoResult>();
using var context = _contextFactory.CreateContext(enableTracking: false);
// we need to get the ratings separately because there's not explicit FK
var ratings = await context.Set<EFClientRatingHistory>()
.Where(_ratingHistory => _ratingHistory.ClientId == query.ClientId)
.SelectMany(_ratingHistory => _ratingHistory.Ratings.Where(_rating => _rating.ServerId != null && _rating.Newest)
.Select(_rating => new
{
_rating.ServerId,
_rating.Ranking,
_rating.When
}))
.ToListAsync();
var iqStats = context.Set<EFClientStatistics>()
.Where(_stats => _stats.ClientId == query.ClientId)
.Select(_stats => new StatsInfoResult
{
ServerId = _stats.ServerId,
Kills = _stats.Kills,
Deaths = _stats.Deaths,
Performance = Math.Round((_stats.EloRating + _stats.Skill) / 2.0, 2),
ScorePerMinute = _stats.SPM,
LastPlayed = _stats.Client.LastConnection,
TotalSecondsPlayed = _stats.TimePlayed,
ServerGame = _stats.Server.GameName.ToString(),
ServerName = _stats.Server.HostName,
});
var queryResults = await iqStats.ToListAsync();
// add the rating query's results to the full query
foreach(var eachResult in queryResults)
{
var rating = ratings.FirstOrDefault(_rating => _rating.ServerId == eachResult.ServerId);
eachResult.Ranking = rating?.Ranking ?? 0;
eachResult.LastPlayed = rating?.When ?? eachResult.LastPlayed;
}
result.Results = queryResults;
result.RetrievedResultCount = queryResults.Count;
result.TotalResultCount = result.RetrievedResultCount;
return result;
}
}
}

View File

@ -12,11 +12,11 @@
<Description>Client Statistics Plugin for IW4MAdmin</Description> <Description>Client Statistics Plugin for IW4MAdmin</Description>
<Copyright>2018</Copyright> <Copyright>2018</Copyright>
<Configurations>Debug;Release;Prerelease</Configurations> <Configurations>Debug;Release;Prerelease</Configurations>
<LangVersion>7.1</LangVersion> <LangVersion>8.0</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.12" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -0,0 +1,69 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SharedLibraryCore;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Interfaces;
using Stats.Dtos;
using System;
using System.Threading.Tasks;
namespace StatsWeb.API
{
[ApiController]
[Route("api/stats")]
public class StatsController : ControllerBase
{
private readonly ILogger _logger;
private readonly IResourceQueryHelper<StatsInfoRequest, StatsInfoResult> _statsQueryHelper;
public StatsController(ILogger logger, IResourceQueryHelper<StatsInfoRequest, StatsInfoResult> statsQueryHelper)
{
_statsQueryHelper = statsQueryHelper;
_logger = logger;
}
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[HttpGet("{clientId}")]
public async Task<IActionResult> ClientStats(int clientId)
{
if (clientId < 1 || !ModelState.IsValid)
{
return BadRequest(new ErrorResponse
{
Messages = new[] { $"Client Id must be between 1 and {int.MaxValue}" }
});
}
var request = new StatsInfoRequest()
{
ClientId = clientId
};
try
{
var result = await _statsQueryHelper.QueryResource(request);
if (result.RetrievedResultCount == 0)
{
return NotFound();
}
return Ok(result.Results);
}
catch (Exception e)
{
_logger.WriteWarning($"Could not get client stats for client id {clientId}");
_logger.WriteDebug(e.GetExceptionInfo());
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse
{
Messages = new[] { e.Message }
});
}
}
}
}

View File

@ -14,7 +14,7 @@
<RunPostBuildEvent>Always</RunPostBuildEvent> <RunPostBuildEvent>Always</RunPostBuildEvent>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.0" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -16,7 +16,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.11" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.4.2" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -24,5 +24,8 @@ namespace SharedLibraryCore.Database.Models
[NotMapped] [NotMapped]
public const int MAX_NAME_LENGTH = 24; public const int MAX_NAME_LENGTH = 24;
[NotMapped]
public const int MIN_NAME_LENGTH = 3;
} }
} }

View File

@ -0,0 +1,15 @@
namespace SharedLibraryCore.Dtos
{
public class ErrorResponse
{
/// <summary>
/// todo: type of error
/// </summary>
public string Type { get; set; }
/// <summary>
/// relevant error messages
/// </summary>
public string[] Messages { get; set; }
}
}

View File

@ -0,0 +1,17 @@
namespace SharedLibraryCore.Dtos
{
public class FindClientRequest : PaginationInfo
{
/// <summary>
/// name of client
/// </summary>
public string Name { get; set; }
/// <summary>
/// network id of client
/// </summary>
public string Xuid { get; set; }
public string ToDebugString() => $"[Name={Name}, Xuid={Xuid}]";
}
}

View File

@ -0,0 +1,20 @@
namespace SharedLibraryCore.Dtos
{
public class FindClientResult
{
/// <summary>
/// client identifier
/// </summary>
public int ClientId { get; set; }
/// <summary>
/// networkid of client
/// </summary>
public string Xuid { get; set; }
/// <summary>
/// name of client
/// </summary>
public string Name { get; set; }
}
}

View File

@ -13,7 +13,7 @@
/// <summary> /// <summary>
/// how many itesm to take /// how many itesm to take
/// </summary> /// </summary>
public int Count { get; set; } public int Count { get; set; } = 100;
/// <summary> /// <summary>
/// filter query /// filter query

View File

@ -2,6 +2,8 @@
using SharedLibraryCore.Database; using SharedLibraryCore.Database;
using SharedLibraryCore.Database.Models; using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos; using SharedLibraryCore.Dtos;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -10,8 +12,15 @@ using static SharedLibraryCore.Database.Models.EFClient;
namespace SharedLibraryCore.Services namespace SharedLibraryCore.Services
{ {
public class ClientService : Interfaces.IEntityService<EFClient> public class ClientService : IEntityService<EFClient>, IResourceQueryHelper<FindClientRequest, FindClientResult>
{ {
private readonly IDatabaseContextFactory _contextFactory;
public ClientService(IDatabaseContextFactory databaseContextFactory)
{
_contextFactory = databaseContextFactory;
}
public async Task<EFClient> Create(EFClient entity) public async Task<EFClient> Create(EFClient entity)
{ {
using (var context = new DatabaseContext()) using (var context = new DatabaseContext())
@ -724,5 +733,56 @@ namespace SharedLibraryCore.Services
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
} }
} }
/// <summary>
/// find clients matching the given query
/// </summary>
/// <param name="query">query filters</param>
/// <returns></returns>
public async Task<ResourceQueryHelperResult<FindClientResult>> QueryResource(FindClientRequest query)
{
var result = new ResourceQueryHelperResult<FindClientResult>();
using var context = _contextFactory.CreateContext(enableTracking: false);
IQueryable<EFClient> iqClients = null;
if (!string.IsNullOrEmpty(query.Xuid))
{
long networkId = query.Xuid.ConvertGuidToLong(System.Globalization.NumberStyles.HexNumber);
iqClients = context.Clients.Where(_client => _client.NetworkId == networkId);
}
else if (!string.IsNullOrEmpty(query.Name))
{
iqClients = context.Clients.Where(_client => EF.Functions.Like(_client.CurrentAlias.Name.ToLower(), $"%{query.Name.ToLower()}%"));
}
if (query.Direction == SortDirection.Ascending)
{
iqClients = iqClients.OrderBy(_client => _client.LastConnection);
}
else
{
iqClients = iqClients.OrderByDescending(_client => _client.LastConnection);
}
var queryResults = await iqClients
.Select(_client => new FindClientResult
{
ClientId = _client.ClientId,
Xuid = _client.NetworkId.ToString("X"),
Name = _client.CurrentAlias.Name
})
.Skip(query.Offset)
.Take(query.Count)
.ToListAsync();
result.TotalResultCount = await iqClients.CountAsync();
result.Results = queryResults;
result.RetrievedResultCount = queryResults.Count;
return result;
}
} }
} }

View File

@ -6,12 +6,12 @@
<ApplicationIcon /> <ApplicationIcon />
<StartupObject /> <StartupObject />
<PackageId>RaidMax.IW4MAdmin.SharedLibraryCore</PackageId> <PackageId>RaidMax.IW4MAdmin.SharedLibraryCore</PackageId>
<Version>2.4.0</Version> <Version>2.4.2</Version>
<Authors>RaidMax</Authors> <Authors>RaidMax</Authors>
<Company>Forever None</Company> <Company>Forever None</Company>
<Configurations>Debug;Release;Prerelease</Configurations> <Configurations>Debug;Release;Prerelease</Configurations>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest> <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
<LangVersion>7.1</LangVersion> <LangVersion>8.0</LangVersion>
<PackageTags>IW4MAdmin</PackageTags> <PackageTags>IW4MAdmin</PackageTags>
<RepositoryUrl>https://github.com/RaidMax/IW4M-Admin/</RepositoryUrl> <RepositoryUrl>https://github.com/RaidMax/IW4M-Admin/</RepositoryUrl>
<PackageProjectUrl>https://www.raidmax.org/IW4MAdmin/</PackageProjectUrl> <PackageProjectUrl>https://www.raidmax.org/IW4MAdmin/</PackageProjectUrl>
@ -20,8 +20,6 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<Description>Shared Library for IW4MAdmin</Description> <Description>Shared Library for IW4MAdmin</Description>
<AssemblyVersion>2.4.0.0</AssemblyVersion>
<FileVersion>2.4.0.0</FileVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Prerelease|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Prerelease|AnyCPU'">
@ -29,22 +27,6 @@
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Migrations\20181126232438_AddEndpointToEFServer.cs" />
<Compile Remove="Migrations\20181126233300_AddEndpointToEFServer.cs" />
<Compile Remove="Migrations\20181127143920_AddEndpointToEFServerUpdateServerIdType.cs" />
<Compile Remove="Migrations\20190222234606_AddIndexToEFMeta-KeyAndClientId.cs" />
<Compile Remove="Migrations\20190223012312_SetMaxLengthForMetaKey.cs" />
<Compile Remove="Migrations\20190907222702_AddMomentViewAnglesToAcSnapshot.cs" />
<Compile Remove="Migrations\20190907222702_AddMomentViewAnglesToAcSnapshot.Designer.cs" />
<Compile Remove="Migrations\20191120170503_AddDateAuditColumnsToSharedEntity.cs" />
<Compile Remove="Migrations\20191120170503_AddDateAuditColumnsToSharedEntity.Designer.cs" />
<Compile Remove="Migrations\20191120204934_AddDateAuditColumnsToSharedEntity.cs" />
<Compile Remove="Migrations\20191120204934_AddDateAuditColumnsToSharedEntity.Designer.cs" />
<Compile Remove="Migrations\20191120205633_AddDateAuditColumnsToSharedEntity.cs" />
<Compile Remove="Migrations\20191120205633_AddDateAuditColumnsToSharedEntity.Designer.cs" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentValidation" Version="8.6.2" /> <PackageReference Include="FluentValidation" Version="8.6.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />

View File

@ -0,0 +1,203 @@
using ApplicationTests.Fixtures;
using FakeItEasy;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using Stats.Dtos;
using StatsWeb.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebfrontCore.Controllers.API;
using WebfrontCore.Controllers.API.Dtos;
using WebfrontCore.Controllers.API.Validation;
namespace ApplicationTests
{
[TestFixture]
public class ApiTests
{
private IServiceProvider serviceProvider;
private IDatabaseContextFactory contextFactory;
private ClientController clientController;
private StatsWeb.API.StatsController statsController;
private IResourceQueryHelper<FindClientRequest, FindClientResult> fakeClientQueryHelper;
private IResourceQueryHelper<StatsInfoRequest, StatsInfoResult> fakeStatsQueryHelper;
[SetUp]
public void Setup()
{
var collection = new ServiceCollection();
collection.AddMvc()
.AddFluentValidation();
serviceProvider = collection.AddSingleton<ClientController>()
.AddSingleton<StatsWeb.API.StatsController>()
.AddSingleton(A.Fake<IResourceQueryHelper<FindClientRequest, FindClientResult>>())
.AddSingleton(A.Fake<IResourceQueryHelper<StatsInfoRequest, StatsInfoResult>>())
.AddTransient<IValidator<FindClientRequest>, FindClientRequestValidator>()
.BuildBase()
.BuildServiceProvider();
clientController = serviceProvider.GetRequiredService<ClientController>();
statsController = serviceProvider.GetRequiredService<StatsWeb.API.StatsController>();
contextFactory = serviceProvider.GetRequiredService<IDatabaseContextFactory>();
fakeClientQueryHelper = serviceProvider.GetRequiredService<IResourceQueryHelper<FindClientRequest, FindClientResult>>();
fakeStatsQueryHelper = serviceProvider.GetRequiredService<IResourceQueryHelper<StatsInfoRequest, StatsInfoResult>>();
}
#region CLIENT_CONTROLLER
[Test]
public async Task Test_ClientController_FindAsync_Happy()
{
var query = new FindClientRequest()
{
Name = "test"
};
int expectedClientId = 123;
A.CallTo(() => fakeClientQueryHelper.QueryResource(A<FindClientRequest>.Ignored))
.Returns(Task.FromResult(new ResourceQueryHelperResult<FindClientResult>()
{
Results = new[]
{
new FindClientResult()
{
ClientId = expectedClientId
}
}
}));
var result = await clientController.FindAsync(query);
Assert.IsInstanceOf<OkObjectResult>(result);
var viewResult = (result as OkObjectResult).Value as FindClientResponse;
Assert.NotNull(viewResult);
Assert.AreEqual(expectedClientId, viewResult.Clients.First().ClientId);
}
[Test]
public async Task Test_ClientController_FindAsync_InvalidModelState()
{
var query = new FindClientRequest();
clientController.ModelState.AddModelError("test", "test");
var result = await clientController.FindAsync(query);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
clientController.ModelState.Clear();
}
[Test]
public async Task Test_ClientController_FindAsync_Exception()
{
string expectedExceptionMessage = "failure";
int expectedStatusCode = 500;
var query = new FindClientRequest();
A.CallTo(() => fakeClientQueryHelper.QueryResource(A<FindClientRequest>.Ignored))
.Throws(new Exception(expectedExceptionMessage));
var result = await clientController.FindAsync(query);
Assert.IsInstanceOf<ObjectResult>(result);
var statusResult = (result as ObjectResult);
Assert.AreEqual(expectedStatusCode, statusResult.StatusCode);
//Assert.IsTrue((statusResult.Value as ErrorResponse).Messages.Contains(expectedExceptionMessage));
}
#endregion
#region STATS_CONTROLLER
[Test]
public async Task Test_StatsController_ClientStats_Happy()
{
var client = ClientGenerators.CreateBasicClient(null);
var query = new StatsInfoRequest
{
ClientId = client.ClientId
};
var queryResult = new ResourceQueryHelperResult<StatsInfoResult>()
{
Results = new[]
{
new StatsInfoResult
{
Deaths = 1,
Kills = 1,
LastPlayed = DateTime.Now,
Performance = 100,
Ranking = 10,
ScorePerMinute = 500,
ServerGame = "IW4",
ServerId = 123,
ServerName = "IW4Host",
TotalSecondsPlayed = 100
}
},
TotalResultCount = 1,
RetrievedResultCount = 1
};
A.CallTo(() => fakeStatsQueryHelper.QueryResource(A<StatsInfoRequest>.Ignored))
.Returns(Task.FromResult(queryResult));
var result = await statsController.ClientStats(query.ClientId.Value);
Assert.IsInstanceOf<OkObjectResult>(result);
var viewResult = (result as OkObjectResult).Value as IEnumerable<StatsInfoResult>;
Assert.NotNull(viewResult);
Assert.AreEqual(queryResult.Results, viewResult);
}
[Test]
public async Task Test_StatsController_ClientStats_InvalidModelState()
{
statsController.ModelState.AddModelError("test", "test");
var result = await statsController.ClientStats(1);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
statsController.ModelState.Clear();
}
[Test]
public async Task Test_StatsController_ClientStats_Exception()
{
string expectedExceptionMessage = "failure";
int expectedStatusCode = 500;
A.CallTo(() => fakeStatsQueryHelper.QueryResource(A<StatsInfoRequest>.Ignored))
.Throws(new Exception(expectedExceptionMessage));
var result = await statsController.ClientStats(1);
Assert.IsInstanceOf<ObjectResult>(result);
var statusResult = (result as ObjectResult);
Assert.AreEqual(expectedStatusCode, statusResult.StatusCode);
Assert.IsTrue((statusResult.Value as ErrorResponse).Messages.Contains(expectedExceptionMessage));
}
[Test]
public async Task Test_StatsController_ClientStats_NotFound()
{
var queryResult = new ResourceQueryHelperResult<StatsInfoResult>()
{
Results = new List<StatsInfoResult>()
};
A.CallTo(() => fakeStatsQueryHelper.QueryResource(A<StatsInfoRequest>.Ignored))
.Returns(Task.FromResult(queryResult));
var result = await statsController.ClientStats(1);
Assert.IsInstanceOf<NotFoundResult>(result);
}
#endregion
}
}

View File

@ -2,6 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
<LangVersion>8.0</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -37,6 +37,7 @@ namespace ApplicationTests
serviceProvider = new ServiceCollection() serviceProvider = new ServiceCollection()
.BuildBase(new EventHandlerMock(true)) .BuildBase(new EventHandlerMock(true))
.AddSingleton(A.Fake<ClientService>())
.BuildServiceProvider() .BuildServiceProvider()
.SetupTestHooks(); .SetupTestHooks();

View File

@ -42,7 +42,6 @@ namespace ApplicationTests
.AddSingleton(A.Fake<IRConParser>()) .AddSingleton(A.Fake<IRConParser>())
.AddSingleton(A.Fake<IParserRegexFactory>()) .AddSingleton(A.Fake<IParserRegexFactory>())
.AddSingleton<DataFileLoader>() .AddSingleton<DataFileLoader>()
.AddSingleton(A.Fake<ClientService>())
.AddSingleton(A.Fake<IGameLogReaderFactory>()) .AddSingleton(A.Fake<IGameLogReaderFactory>())
.AddSingleton(eventHandler) .AddSingleton(eventHandler)
.AddSingleton(ConfigurationGenerators.CreateApplicationConfiguration()) .AddSingleton(ConfigurationGenerators.CreateApplicationConfiguration())

View File

@ -31,6 +31,7 @@ namespace ApplicationTests
public void Setup() public void Setup()
{ {
serviceProvider = new ServiceCollection().BuildBase() serviceProvider = new ServiceCollection().BuildBase()
.AddSingleton(A.Fake<ClientService>())
.AddSingleton<IScriptCommandFactory, ScriptCommandFactory>() .AddSingleton<IScriptCommandFactory, ScriptCommandFactory>()
.BuildServiceProvider(); .BuildServiceProvider();
fakeManager = serviceProvider.GetRequiredService<IManager>(); fakeManager = serviceProvider.GetRequiredService<IManager>();

View File

@ -0,0 +1,173 @@
using ApplicationTests.Fixtures;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApplicationTests
{
[TestFixture]
public class ServiceTests
{
private IServiceProvider serviceProvider;
private IDatabaseContextFactory contextFactory;
private ClientService clientService;
[SetUp]
public void Setup()
{
serviceProvider = new ServiceCollection()
.AddSingleton<ClientService>()
.BuildBase()
.BuildServiceProvider();
contextFactory = serviceProvider.GetRequiredService<IDatabaseContextFactory>();
clientService = serviceProvider.GetRequiredService<ClientService>();
}
#region QUERY_RESOURCE
[Test]
public async Task Test_QueryClientResource_Xuid()
{
var client = ClientGenerators.CreateBasicClient(null);
client.NetworkId = -1;
var query = new FindClientRequest()
{
Xuid = client.NetworkId.ToString("X")
};
using var context = contextFactory.CreateContext();
context.Clients.Add(client);
await context.SaveChangesAsync();
var result = await clientService.QueryResource(query);
Assert.IsNotEmpty(result.Results);
Assert.AreEqual(query.Xuid, result.Results.First().Xuid);
context.Clients.Remove(client);
await context.SaveChangesAsync();
}
[Test]
public async Task Test_QueryClientResource_NameExactMatch()
{
var query = new FindClientRequest()
{
Name = "test"
};
using var context = contextFactory.CreateContext();
var client = ClientGenerators.CreateBasicClient(null);
client.Name = query.Name;
context.Clients.Add(client);
await context.SaveChangesAsync();
var result = await clientService.QueryResource(query);
Assert.IsNotEmpty(result.Results);
Assert.AreEqual(query.Name, result.Results.First().Name);
context.Clients.Remove(client);
await context.SaveChangesAsync();
}
[Test]
public async Task Test_QueryClientResource_NameCaseInsensitivePartial()
{
var query = new FindClientRequest()
{
Name = "TEST"
};
using var context = contextFactory.CreateContext();
var client = ClientGenerators.CreateBasicClient(null);
client.Name = "atesticle";
context.Clients.Add(client);
await context.SaveChangesAsync();
var result = await clientService.QueryResource(query);
Assert.IsNotEmpty(result.Results);
Assert.IsTrue(result.Results.First().Name.ToUpper().Contains(query.Name));
context.Clients.Remove(client);
await context.SaveChangesAsync();
}
[Test]
public async Task Test_QueryClientResource_SortDirection()
{
var firstClient = ClientGenerators.CreateBasicClient(null);
firstClient.ClientId = 0;
firstClient.NetworkId = -1;
firstClient.LastConnection = DateTime.Now.AddHours(-1);
firstClient.Name = "test";
var secondClient = ClientGenerators.CreateBasicClient(null);
secondClient.ClientId = 0;
secondClient.NetworkId = -2;
secondClient.LastConnection = DateTime.Now;
secondClient.Name = firstClient.Name;
var query = new FindClientRequest()
{
Name = firstClient.Name
};
using var context = contextFactory.CreateContext();
context.Clients.Add(firstClient);
context.Clients.Add(secondClient);
await context.SaveChangesAsync();
var result = await clientService.QueryResource(query);
Assert.IsNotEmpty(result.Results);
Assert.AreEqual(secondClient.NetworkId.ToString("X"), result.Results.First().Xuid);
Assert.AreEqual(firstClient.NetworkId.ToString("X"), result.Results.Last().Xuid);
query.Direction = SortDirection.Ascending;
result = await clientService.QueryResource(query);
Assert.IsNotEmpty(result.Results);
Assert.AreEqual(firstClient.NetworkId.ToString("X"), result.Results.First().Xuid);
Assert.AreEqual(secondClient.NetworkId.ToString("X"), result.Results.Last().Xuid);
context.Clients.Remove(firstClient);
context.Clients.Remove(secondClient);
await context.SaveChangesAsync();
}
[Test]
public async Task Test_QueryClientResource_NoMatch()
{
var query = new FindClientRequest()
{
Name = "test"
};
using var context = contextFactory.CreateContext();
var client = ClientGenerators.CreateBasicClient(null);
client.Name = "client";
context.Clients.Add(client);
await context.SaveChangesAsync();
var result = await clientService.QueryResource(query);
Assert.IsEmpty(result.Results);
context.Clients.Remove(client);
await context.SaveChangesAsync();
}
#endregion
}
}

View File

@ -14,6 +14,8 @@ using Microsoft.Extensions.DependencyInjection;
using IW4MAdmin.Plugins.Stats.Helpers; using IW4MAdmin.Plugins.Stats.Helpers;
using ApplicationTests.Fixtures; using ApplicationTests.Fixtures;
using System.Threading.Tasks; using System.Threading.Tasks;
using Stats.Helpers;
using Stats.Dtos;
namespace ApplicationTests namespace ApplicationTests
{ {
@ -23,6 +25,7 @@ namespace ApplicationTests
ILogger logger; ILogger logger;
private IServiceProvider serviceProvider; private IServiceProvider serviceProvider;
private IConfigurationHandlerFactory handlerFactory; private IConfigurationHandlerFactory handlerFactory;
private IDatabaseContextFactory contextFactory;
[SetUp] [SetUp]
public void Setup() public void Setup()
@ -31,10 +34,13 @@ namespace ApplicationTests
handlerFactory = A.Fake<IConfigurationHandlerFactory>(); handlerFactory = A.Fake<IConfigurationHandlerFactory>();
serviceProvider = new ServiceCollection() serviceProvider = new ServiceCollection()
.AddSingleton<StatsResourceQueryHelper>()
.BuildBase() .BuildBase()
.AddSingleton<IW4MAdmin.Plugins.Stats.Plugin>() .AddSingleton<IW4MAdmin.Plugins.Stats.Plugin>()
.BuildServiceProvider(); .BuildServiceProvider();
contextFactory = serviceProvider.GetRequiredService<IDatabaseContextFactory>();
void testLog(string msg) => Console.WriteLine(msg); void testLog(string msg) => Console.WriteLine(msg);
A.CallTo(() => logger.WriteError(A<string>.Ignored)).Invokes((string msg) => testLog(msg)); A.CallTo(() => logger.WriteError(A<string>.Ignored)).Invokes((string msg) => testLog(msg));
@ -155,5 +161,55 @@ namespace ApplicationTests
await mgr.UpdateStatHistory(target, stats); await mgr.UpdateStatHistory(target, stats);
} }
#region QUERY_HELPER
[Test]
public async Task Test_StatsQueryHelper_Get()
{
var queryHelper = serviceProvider.GetRequiredService<StatsResourceQueryHelper>();
using var context = contextFactory.CreateContext();
var server = new EFServer() { ServerId = 1 };
var stats = new EFClientStatistics()
{
Client = ClientGenerators.CreateBasicClient(null),
SPM = 100,
Server = server
};
var ratingHistory = new EFClientRatingHistory()
{
Client = stats.Client,
Ratings = new[]
{
new EFRating()
{
Ranking = 100,
Server = server,
Newest = true
}
}
};
context.Set<EFClientStatistics>().Add(stats);
context.Set<EFClientRatingHistory>().Add(ratingHistory);
await context.SaveChangesAsync();
var query = new StatsInfoRequest()
{
ClientId = stats.Client.ClientId
};
var result = await queryHelper.QueryResource(query);
Assert.IsNotEmpty(result.Results);
Assert.AreEqual(stats.SPM, result.Results.First().ScorePerMinute);
Assert.AreEqual(ratingHistory.Ratings.First().Ranking, result.Results.First().Ranking);
context.Set<EFClientStatistics>().Remove(stats);
context.Set<EFClientRatingHistory>().Remove(ratingHistory);
context.Set<EFServer>().Remove(server);
await context.SaveChangesAsync();
}
#endregion
} }
} }

View File

@ -0,0 +1,66 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SharedLibraryCore;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Interfaces;
using System;
using System.Linq;
using System.Threading.Tasks;
using WebfrontCore.Controllers.API.Dtos;
namespace WebfrontCore.Controllers.API
{
/// <summary>
/// api controller for client operations
/// </summary>
[ApiController]
[Route("api/client")]
public class ClientController : ControllerBase
{
private readonly IResourceQueryHelper<FindClientRequest, FindClientResult> _clientQueryHelper;
private readonly ILogger _logger;
public ClientController(ILogger logger, IResourceQueryHelper<FindClientRequest, FindClientResult> clientQueryHelper)
{
_logger = logger;
_clientQueryHelper = clientQueryHelper;
}
[HttpGet("find")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> FindAsync([FromQuery]FindClientRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(new ErrorResponse()
{
Messages = ModelState.Values.SelectMany(_value => _value.Errors.Select(_error => _error.ErrorMessage)).ToArray()
});
}
try
{
var results = await _clientQueryHelper.QueryResource(request);
return Ok(new FindClientResponse
{
TotalFoundClients = results.TotalResultCount,
Clients = results.Results
});
}
catch (Exception e)
{
_logger.WriteWarning($"Failed to retrieve clients with query - {request.ToDebugString()}");
_logger.WriteDebug(e.GetExceptionInfo());
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse()
{
Messages = new[] { e.Message }
});
}
}
}
}

View File

@ -0,0 +1,18 @@
using SharedLibraryCore.Dtos;
using System.Collections.Generic;
namespace WebfrontCore.Controllers.API.Dtos
{
public class FindClientResponse
{
/// <summary>
/// total number of client found matching the query
/// </summary>
public long TotalFoundClients { get; set; }
/// <summary>
/// collection of doun clients
/// </summary>
public IEnumerable<FindClientResult> Clients { get; set; }
}
}

View File

@ -0,0 +1,33 @@
using FluentValidation;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos;
namespace WebfrontCore.Controllers.API.Validation
{
/// <summary>
/// validator for FindClientRequest
/// </summary>
public class FindClientRequestValidator : AbstractValidator<FindClientRequest>
{
public FindClientRequestValidator()
{
RuleFor(_request => _request.Name)
.NotEmpty()
.When(_request => string.IsNullOrEmpty(_request.Xuid));
RuleFor(_request => _request.Name)
.MinimumLength(EFAlias.MIN_NAME_LENGTH)
.MaximumLength(EFAlias.MAX_NAME_LENGTH);
RuleFor(_request => _request.Xuid)
.NotEmpty()
.When(_request => string.IsNullOrEmpty(_request.Name));
RuleFor(_request => _request.Count)
.InclusiveBetween(1, 100);
RuleFor(_request => _request.Offset)
.GreaterThanOrEqualTo(0);
}
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Authentication.Cookies; using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
@ -9,8 +11,12 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SharedLibraryCore; using SharedLibraryCore;
using SharedLibraryCore.Database; using SharedLibraryCore.Database;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Helpers; using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Services;
using Stats.Dtos;
using Stats.Helpers;
using StatsWeb; using StatsWeb;
using StatsWeb.Dtos; using StatsWeb.Dtos;
using System.Collections.Generic; using System.Collections.Generic;
@ -19,6 +25,8 @@ using System.Linq;
using System.Net; using System.Net;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using WebfrontCore.Controllers.API.Dtos;
using WebfrontCore.Controllers.API.Validation;
using WebfrontCore.Middleware; using WebfrontCore.Middleware;
namespace WebfrontCore namespace WebfrontCore
@ -55,6 +63,7 @@ namespace WebfrontCore
// Add framework services. // Add framework services.
var mvcBuilder = services.AddMvc(_options => _options.SuppressAsyncSuffixInActionNames = false) var mvcBuilder = services.AddMvc(_options => _options.SuppressAsyncSuffixInActionNames = false)
.AddFluentValidation()
.ConfigureApplicationPartManager(_partManager => .ConfigureApplicationPartManager(_partManager =>
{ {
foreach (var assembly in pluginAssemblies()) foreach (var assembly in pluginAssemblies())
@ -105,6 +114,9 @@ namespace WebfrontCore
services.AddSingleton(Program.Manager); services.AddSingleton(Program.Manager);
services.AddSingleton<IResourceQueryHelper<ChatSearchQuery, ChatSearchResult>, ChatResourceQueryHelper>(); services.AddSingleton<IResourceQueryHelper<ChatSearchQuery, ChatSearchResult>, ChatResourceQueryHelper>();
services.AddTransient<IValidator<FindClientRequest>, FindClientRequestValidator>();
services.AddSingleton<IResourceQueryHelper<FindClientRequest, FindClientResult>, ClientService>();
services.AddSingleton<IResourceQueryHelper<StatsInfoRequest, StatsInfoResult>, StatsResourceQueryHelper>();
// todo: this needs to be handled more gracefully // todo: this needs to be handled more gracefully
services.AddSingleton(Program.ApplicationServiceProvider.GetService<IConfigurationHandlerFactory>()); services.AddSingleton(Program.ApplicationServiceProvider.GetService<IConfigurationHandlerFactory>());

View File

@ -66,6 +66,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="BuildBundlerMinifier" Version="3.2.435" /> <PackageReference Include="BuildBundlerMinifier" Version="3.2.435" />
<PackageReference Include="BuildWebCompiler" Version="1.12.405" /> <PackageReference Include="BuildWebCompiler" Version="1.12.405" />
<PackageReference Include="FluentValidation.AspNetCore" Version="8.6.2" />
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.0.96" /> <PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.0.96" />
</ItemGroup> </ItemGroup>