Add new agnostic challonge provider

This commit is contained in:
2022-03-20 19:36:15 +01:00
parent 92b6d3e568
commit ee48b7d75c
17 changed files with 561 additions and 314 deletions

View File

@@ -18,12 +18,12 @@ namespace LaDOSE.Api.Controllers
public class SmashController : Controller public class SmashController : Controller
{ {
private IEventService _service; private IExternalProviderService _service;
private IMapper _mapper; private IMapper _mapper;
// GET // GET
public SmashController(IMapper mapper, IEventService service) public SmashController(IMapper mapper, IExternalProviderService service)
{ {
_mapper = mapper; _mapper = mapper;
_service = service; _service = service;

View File

@@ -18,12 +18,12 @@ namespace LaDOSE.Api.Controllers
public class TestController : Controller public class TestController : Controller
{ {
private IEventService _service; private IExternalProviderService _service;
private IMapper _mapper; private IMapper _mapper;
// GET // GET
public TestController(IMapper mapper, IEventService service) public TestController(IMapper mapper, IExternalProviderService service)
{ {
_mapper = mapper; _mapper = mapper;
_service = service; _service = service;

View File

@@ -15,12 +15,12 @@ namespace LaDOSE.Api.Controllers
public class TournamentController : Controller public class TournamentController : Controller
{ {
private IEventService _service; private IExternalProviderService _service;
private IMapper _mapper; private IMapper _mapper;
// GET // GET
public TournamentController(IMapper mapper, IEventService service) public TournamentController(IMapper mapper, IExternalProviderService service)
{ {
_mapper = mapper; _mapper = mapper;
_service = service; _service = service;
@@ -48,9 +48,11 @@ namespace LaDOSE.Api.Controllers
throw new Exception("Invalid arguments"); throw new Exception("Invalid arguments");
} }
var tournamentsResult = await _service.GetTournamentsResult(ids); var test = await _service.GetChallongeEvents(ids);
return _mapper.Map<TournamentsResultDTO>(tournamentsResult); //var tournamentsResult = await _service.GetTournamentsResult(ids);
return _mapper.Map<TournamentsResultDTO>(new TournamentsResultDTO());
} }

View File

@@ -142,7 +142,6 @@ namespace LaDOSE.Api
private void AddDIConfig(IServiceCollection services) private void AddDIConfig(IServiceCollection services)
{ {
services.AddTransient<IChallongeProvider>(p => new ChallongeProvider(this.Configuration["ApiKey:ChallongeApiKey"]));
services.AddScoped<IUserService, UserService>(); services.AddScoped<IUserService, UserService>();
services.AddScoped<IGameService, GameService>(); services.AddScoped<IGameService, GameService>();
@@ -150,8 +149,18 @@ namespace LaDOSE.Api
services.AddScoped<IWordPressService, WordPressService>(); services.AddScoped<IWordPressService, WordPressService>();
services.AddScoped<ITodoService, TodoService>(); services.AddScoped<ITodoService, TodoService>();
services.AddScoped<IEventService, EventService>(); services.AddScoped<IEventService, EventService>();
services.AddScoped<IPlayerService, PlayerService>(); services.AddScoped<IPlayerService, PlayerService>();
services.AddScoped<ISmashProvider>(p => new SmashProvider(p.GetRequiredService<IGameService>(), p.GetRequiredService<IPlayerService>(), this.Configuration["ApiKey:SmashApiKey"])); services.AddTransient<IChallongeProvider>(p => new ChallongeProvider( p.GetRequiredService<IGameService>(),
p.GetRequiredService<IEventService>(),
p.GetRequiredService<IPlayerService>(),
this.Configuration["ApiKey:ChallongeApiKey"]));
services.AddTransient<ISmashProvider>(p => new SmashProvider( p.GetRequiredService<IGameService>(),
p.GetRequiredService<IEventService>(),
p.GetRequiredService<IPlayerService>(),
this.Configuration["ApiKey:SmashApiKey"]));
services.AddScoped<IExternalProviderService, ExternalProviderService>();
} }

View File

@@ -10,7 +10,7 @@ namespace LaDOSE.Entity
{ {
} }
public Tournament(string name, int challongeId, int smashId) public Tournament(string name, int? challongeId, int? smashId)
{ {
Name = name; Name = name;
ChallongeId = challongeId; ChallongeId = challongeId;
@@ -20,8 +20,8 @@ namespace LaDOSE.Entity
public int EventId { get; set; } public int EventId { get; set; }
public Event Event { get; set; } public Event Event { get; set; }
public String Name { get; set; } public String Name { get; set; }
public int ChallongeId {get;set;} public int? ChallongeId {get;set;}
public int SmashId {get;set;} public int? SmashId {get;set;}
public int? GameId {get;set;} public int? GameId {get;set;}
public Game Game { get; set; } public Game Game { get; set; }

View File

@@ -29,6 +29,9 @@ namespace LaDOSE.REST
public void Connect(Uri url, string user, string password) public void Connect(Uri url, string user, string password)
{ {
Client = new RestClient(url); Client = new RestClient(url);
#if DEBUG
Client.Timeout = 99*1000;
#endif
this.username = user; this.username = user;
this.password = password; this.password = password;
GetToken(user, password); GetToken(user, password);

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChallongeCSharpDriver.Core.Results; using ChallongeCSharpDriver.Core.Results;
using LaDOSE.Entity;
using LaDOSE.Entity.Challonge; using LaDOSE.Entity.Challonge;
namespace LaDOSE.Business.Interface namespace LaDOSE.Business.Interface
@@ -17,6 +18,8 @@ namespace LaDOSE.Business.Interface
Task<List<ChallongeParticipent>> GetParticipents(int idTournament); Task<List<ChallongeParticipent>> GetParticipents(int idTournament);
Task<ChallongeTournament> GetTournament(int idTournament); Task<ChallongeTournament> GetTournament(int idTournament);
Task<ChallongeTournament> GetTournament(string urlTournament); Task<ChallongeTournament> GetTournament(string urlTournament);
Task<List<Event>> GetEvents(List<int> idTournaments);
} }
} }

View File

@@ -1,21 +1,13 @@
using System; using LaDOSE.Entity;
using System.Collections.Generic;
using System.Threading.Tasks;
using LaDOSE.Entity;
using LaDOSE.Entity.Challonge;
using LaDOSE.Entity.Wordpress; using LaDOSE.Entity.Wordpress;
namespace LaDOSE.Business.Interface namespace LaDOSE.Business.Interface
{ {
public interface IEventService : IBaseService<Event> public interface IEventService : IBaseService<Event>
{ {
Task<List<ChallongeTournament>> GetTournaments(DateTime? start, DateTime? end);
Task<TournamentsResult> GetTournamentsResult(List<int> ids);
Task<TournamentsResult> GetSmashResult(string tournamentSlug);
Task<TournamentsResult> GetSmashResult2(string tournamentSlug);
Event GetBySlug(string tournamentSlug);
Event GetByName(string name);
} }
} }

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LaDOSE.Entity;
using LaDOSE.Entity.Challonge;
namespace LaDOSE.Business.Interface
{
public interface IExternalProviderService
{
Task<List<ChallongeTournament>> GetTournaments(DateTime? start, DateTime? end);
Task<TournamentsResult> GetTournamentsResult(List<int> ids);
Task<TournamentsResult> GetSmashResult(string tournamentSlug);
Task<TournamentsResult> GetSmashResult2(string tournamentSlug);
Task<List<Event>> GetChallongeEvents(List<int> ids);
}
}

View File

@@ -5,7 +5,7 @@ namespace LaDOSE.Business.Interface
{ {
public interface IGameService : IBaseService<Game> public interface IGameService : IBaseService<Game>
{ {
public int? GetIdByName(string name);
} }
} }

View File

@@ -1,10 +1,12 @@
using LaDOSE.Business.Provider.SmashProvider; using LaDOSE.Business.Provider.SmashProvider;
using LaDOSE.Entity; using LaDOSE.Entity;
using LaDOSE.Entity.Challonge;
namespace LaDOSE.Business.Interface namespace LaDOSE.Business.Interface
{ {
public interface IPlayerService : IBaseService<Player> public interface IPlayerService : IBaseService<Player>
{ {
int GetBySmash(ParticipantType participantUser); int GetIdBySmash(ParticipantType participantUser);
int GetIdByName(ChallongeParticipent challongeParticipent);
} }
} }

View File

@@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using ChallongeCSharpDriver; using ChallongeCSharpDriver;
using ChallongeCSharpDriver.Caller; using ChallongeCSharpDriver.Caller;
@@ -8,6 +10,7 @@ using ChallongeCSharpDriver.Core.Objects;
using ChallongeCSharpDriver.Core.Queries; using ChallongeCSharpDriver.Core.Queries;
using ChallongeCSharpDriver.Core.Results; using ChallongeCSharpDriver.Core.Results;
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.Entity;
using LaDOSE.Entity.Challonge; using LaDOSE.Entity.Challonge;
namespace LaDOSE.Business.Provider.ChallongProvider namespace LaDOSE.Business.Provider.ChallongProvider
@@ -21,15 +24,25 @@ namespace LaDOSE.Business.Provider.ChallongProvider
public string DernierTournois { get; set; } public string DernierTournois { get; set; }
public ChallongeProvider(IGameService gameService, IEventService eventService, IPlayerService playerService, string apiKey)
public ChallongeProvider(string apiKey)
{ {
this.ApiKey = apiKey; this.ApiKey = apiKey;
this.Config = new ChallongeConfig(this.ApiKey); this.Config = new ChallongeConfig(this.ApiKey);
this.ApiCaller = new ChallongeHTTPClientAPICaller(Config); this.ApiCaller = new ChallongeHTTPClientAPICaller(Config);
this.EventService = eventService;
this.GameService = gameService;
this.PlayerService = playerService;
DernierTournois = "Aucun tournois."; DernierTournois = "Aucun tournois.";
} }
public IPlayerService PlayerService { get; set; }
public IGameService GameService { get; set; }
public IEventService EventService { get; set; }
#region Old Provider
public async Task<TournamentResult> CreateTournament(string name, string url, DateTime? startAt = null) public async Task<TournamentResult> CreateTournament(string name, string url, DateTime? startAt = null)
{ {
var result = await new CreateTournamentQuery(name, startAt, TournamentType.Double_Elimination, url).call(ApiCaller); var result = await new CreateTournamentQuery(name, startAt, TournamentType.Double_Elimination, url).call(ApiCaller);
@@ -161,5 +174,116 @@ namespace LaDOSE.Business.Provider.ChallongProvider
{ {
return DernierTournois; return DernierTournois;
} }
#endregion
public Event TryGetEvent(string eventName, string date)
{
var currentevent = this.EventService.GetByName(eventName);
if (currentevent != null) return currentevent;
var Date = new DateTime(1950, 1, 1);
//
try
{
Date = DateTime.ParseExact(date, "dd/MM/yy",
CultureInfo.InvariantCulture);
}
catch (FormatException)
{
//Don't care
}
currentevent = new Event()
{
Name = eventName,
Date = Date,
};
this.EventService.AddOrUpdate(currentevent);
return currentevent;
}
private const string RegexRanking = @"Ranking #\w{3}";
private const string DateRanking = @"^\[(\d{2}\/\d{2}\/\d{2})\]";
private const string GameRanking = @"\-.(\w*)$";
public async Task<List<Event>> GetEvents(List<int> idTournaments)
{
var result = new List<Event>();
foreach (var idTournament in idTournaments)
{
Task<ChallongeTournament> tournament;
try
{
tournament = GetTournament(idTournament);
}
catch
{
continue;
}
if (tournament.Result.Name.Contains("Ranking #"))
{
var eventName = Regex.Match(tournament.Result.Name, RegexRanking);
var eventDate = Regex.Match(tournament.Result.Name, DateRanking);
var tournamentGame = Regex.Match(tournament.Result.Name, GameRanking);
if (eventName.Groups.Count > 0 && eventDate.Groups.Count > 1)
{
var eventNameCapture = eventName.Groups[0].Value;
var eventDateCapture = eventDate.Groups[1].Value;
var currentevent = result.FirstOrDefault(e => e.Name == eventNameCapture);
if (currentevent == null)
{
currentevent = TryGetEvent(eventNameCapture, eventDateCapture);
result.Add(currentevent);
}
string eventGame = tournament.Result.Name;
if (tournamentGame.Groups.Count > 1)
{
eventGame = tournamentGame.Groups[1].Value;
}
if (currentevent.Tournaments == null)
{
currentevent.Tournaments = new List<Tournament>();
}
var currentTournament = currentevent.Tournaments.FirstOrDefault(e => e.Name == eventGame);
if (currentTournament == null)
{
currentTournament = new Tournament(eventGame, tournament.Result.ChallongeId, null)
{
GameId = GameService.GetIdByName(eventGame)
};
List<ChallongeParticipent> participents = new List<ChallongeParticipent>();
try
{
participents = await GetParticipents(tournament.Result.ChallongeId);
}
catch
{
continue;
}
var results = participents.Select(e => new Entity.Result()
{
Tournament = currentTournament,
PlayerId = this.PlayerService.GetIdByName(e),
Rank = e.Rank ?? 999
}).ToList();
currentTournament.Results = results;
currentevent.Tournaments.Add(currentTournament);
}
}
}
}
return result;
}
} }
} }

View File

@@ -20,15 +20,16 @@ namespace LaDOSE.Business.Provider.SmashProvider
//{ //{
// this.ApiKey = apiKey; // this.ApiKey = apiKey;
//} //}
public SmashProvider(IGameService gameService, IPlayerService playerService, string apiKey) public SmashProvider(IGameService gameService, IEventService eventService, IPlayerService playerService, string apiKey)
{ {
this.ApiKey = apiKey; this.ApiKey = apiKey;
this.GameService = gameService; this.GameService = gameService;
this.EventService = eventService;
this.PlayerService = playerService; this.PlayerService = playerService;
} }
public IPlayerService PlayerService { get; set; } public IPlayerService PlayerService { get; set; }
public IEventService EventService { get; set; }
public IGameService GameService { get; set; } public IGameService GameService { get; set; }
private async Task<T> QuerySmash<T>(GraphQLRequest req) private async Task<T> QuerySmash<T>(GraphQLRequest req)
@@ -165,7 +166,7 @@ namespace LaDOSE.Business.Provider.SmashProvider
Tournament = tournament, Tournament = tournament,
TournamentId = tournament.Id, TournamentId = tournament.Id,
PlayerId = PlayerService.GetBySmash(x.player), PlayerId = PlayerService.GetIdBySmash(x.player),
Rank = x.placement Rank = x.placement
}).ToList(); }).ToList();
tournament.Results = res; tournament.Results = res;
@@ -282,8 +283,8 @@ namespace LaDOSE.Business.Provider.SmashProvider
Tournament = tournament, Tournament = tournament,
TournamentId = tournament.Id, TournamentId = tournament.Id,
Player1Id = PlayerService.GetBySmash(x.slots[0].entrant.participants[0]), Player1Id = PlayerService.GetIdBySmash(x.slots[0].entrant.participants[0]),
Player2Id = PlayerService.GetBySmash(x.slots[1].entrant.participants[0]), Player2Id = PlayerService.GetIdBySmash(x.slots[1].entrant.participants[0]),
Player1Score = x.slots[0].standing.stats.score.value, Player1Score = x.slots[0].standing.stats.score.value,
Player2Score = x.slots[1].standing.stats.score.value, Player2Score = x.slots[1].standing.stats.score.value,
Round = x.round ?? 0, Round = x.round ?? 0,

View File

@@ -1,302 +1,29 @@
using System; using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LaDOSE.Business.Helper;
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.Business.Provider.SmashProvider; using LaDOSE.Business.Provider.SmashProvider;
using LaDOSE.Entity; using LaDOSE.Entity;
using LaDOSE.Entity.Challonge;
using LaDOSE.Entity.Context; using LaDOSE.Entity.Context;
using LaDOSE.Entity.Wordpress; using LaDOSE.Entity.Wordpress;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Result = LaDOSE.Entity.Challonge.Result;
namespace LaDOSE.Business.Service namespace LaDOSE.Business.Service
{ {
public class EventService : BaseService<Event>, IEventService public class EventService : BaseService<Event>, IEventService
{ {
private IChallongeProvider _challongeProvider; public EventService(LaDOSEDbContext context ) : base(context)
private ISmashProvider _smashProvider;
#region Rules
private class Rules
{
public int PlayerMin { get; set; }
public int PlayerMax { get; set; }
public int FirstPoint { get; set; }
public int SecondPoint { get; set; }
public int ThirdFourthPoint { get; set; }
public int Top8Point { get; set; }
public int Top16Point { get; set; }
public int Participation => 1;
public Rules(int playerMin, int playerMax, int firstPoint, int secondPoint, int thirdFourthPoint,
int top8Point, int top16Point)
{
PlayerMin = playerMin;
PlayerMax = playerMax;
FirstPoint = firstPoint;
SecondPoint = secondPoint;
ThirdFourthPoint = thirdFourthPoint;
Top8Point = top8Point;
Top16Point = top16Point;
}
}
//Rules Definitions (Min Players,Max Players,First Reward,Second Reward,Third / Fourth Reward, Top 8 reward, Top 16 Reward
private List<Rules> TournamentRules = new List<Rules>()
{
new Rules(0, 8, 5, 3, 2, 0, 0),
new Rules(8, 16, 8, 5, 3, 2, 0),
new Rules(16, 32, 12, 8, 5, 3, 2),
new Rules(32, Int32.MaxValue, 18, 12, 8, 5, 3),
};
#endregion
public EventService(LaDOSEDbContext context, IChallongeProvider challongeProvider, ISmashProvider _smashProvider) : base(context)
{ {
this._context = context; this._context = context;
this._challongeProvider = challongeProvider;
this._smashProvider = _smashProvider;
}
public async Task<List<ChallongeTournament>> GetTournaments(DateTime? start, DateTime? end)
{
return await _challongeProvider.GetTournaments(start, end);
//Useless
//foreach (var tournament in tournaments)
//{
// List<ChallongeParticipent> participents = await _challongeProvider.GetParticipents(tournament.ChallongeId);
// tournament.Participents = participents;
//}
}
public async Task<TournamentsResult> GetTournamentsResult(List<int> ids)
{
TournamentsResult result = new TournamentsResult();
result.Results = new List<Result>();
var players = _context.WPUser.ToList();
var games = _context.Game.ToList();
var tournaments = await GetChallongeTournaments(ids,games);
var allParticipent = tournaments.SelectMany(e => e.Participents).Distinct((a, b) => a.Name == b.Name)
.ToList();
allParticipent.RemoveAll(e => e.Name.StartsWith("[FORFAIT]"));
//USELESS
//foreach (var participent in allParticipent)
//{
// var player = players.FirstOrDefault(e => e.Name.Contains(participent.Name));
// if (player != null)
// {
// participent.IsMember = true;
// }
//}
result.Participents = allParticipent;
foreach (var tournament in tournaments)
{
var playerCount = tournament.Participents.Count;
var lesSacs = tournament.Participents;
var currentRule = TournamentRules.FirstOrDefault(rules =>
rules.PlayerMin < playerCount && rules.PlayerMax >= playerCount
);
if (currentRule == null)
{
throw new Exception("Unable to find rules");
}
var first = tournament.Participents.First(p => p.Rank == 1);
var second = tournament.Participents.First(p => p.Rank == 2);
var thirdFourth = tournament.Participents.Where(p => p.Rank == 3 || p.Rank == 4).ToList();
var Top8 = tournament.Participents.Where(p => p.Rank > 4 && p.Rank < 9).ToList();
var Top16 = tournament.Participents.Where(p => p.Rank > 8 && p.Rank <= 16).ToList();
result.Results.Add(new Result(first.Name, tournament.Game?.Id??0, tournament.ChallongeId, tournament.Url, currentRule.FirstPoint,first.Rank??0));
lesSacs.Remove(first);
result.Results.Add(new Result(second.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.SecondPoint, second.Rank ?? 0));
lesSacs.Remove(second);
thirdFourth.ForEach(r =>
result.Results.Add(new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url,
currentRule.ThirdFourthPoint, r.Rank ?? 0)));
thirdFourth.ForEach(p => lesSacs.Remove(p));
if (currentRule.Top8Point != 0)
{
Top8.ForEach(r =>
result.Results.Add(new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.Top8Point, r.Rank ?? 0)));
Top8.ForEach(p => lesSacs.Remove(p));
}
if (currentRule.Top16Point != 0)
{
Top16.ForEach(r =>
result.Results.Add(
new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.Top16Point, r.Rank ?? 0)));
Top16.ForEach(p => lesSacs.Remove(p));
}
lesSacs.ForEach(r =>
result.Results.Add(new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url,
currentRule.Participation, r.Rank ?? 0)));
}
result.Games = tournaments.Select(e => e.Game).Distinct((game, game1) => game.Name == game1.Name).Where(e=>e!=null).ToList();
if (result.Games == null)
{
result.Games = new List<Game>();
}
result.Games.Add(new Game() {Id = 0, Order = 9999,Name = "UNKNOW"});
return result;
}
public async Task<TournamentsResult> GetSmashResult(string tournamentSlug)
{
var test = this._smashProvider.GetEvent(tournamentSlug).Result;
var testTournaments = test.Tournaments;
var getResultEvents = this._smashProvider.GetResults(ref testTournaments).Result;
getResultEvents = this._smashProvider.GetSets(ref testTournaments).Result;
this._context.Add(test);
this._context.SaveChanges();
var tournaments = await _smashProvider.GetTournament(tournamentSlug);
var players = tournaments.Tournament.Events.Where(e=>e.standings != null ).SelectMany(e => e.standings.nodes.Select(e => e.player)).ToList();
var distinctp = players.DistinctBy(e=>new {e.user.id}).ToList();
var games = _context.Game.ToList();
TournamentsResult result = new TournamentsResult();
result.Results = new List<Result>();
result.Games = new List<Game>();
result.Participents = new List<ChallongeParticipent>();
distinctp.ForEach(e =>
{
var x = new ChallongeParticipent()
{
Name = e.gamerTag,
ChallongeId = e.id,
Id = e.id
};
result.Participents.Add(x);
});
games.ForEach(e =>
{
e.Id = e.SmashId ?? e.Id;
result.Games.Add(e);
});
foreach (var tournament in tournaments.Tournament.Events.Where(e=>e.standings!=null).ToList())
{
var playerCount = tournament.standings.nodes.Count;
var lesSacs = tournament.standings.nodes;
var currentRule = TournamentRules.FirstOrDefault(rules =>
rules.PlayerMin < playerCount && rules.PlayerMax >= playerCount
);
if (currentRule == null)
{
throw new Exception("Unable to find rules");
}
var first = tournament.standings.nodes.First(p => p.placement == 1);
var second = tournament.standings.nodes.First(p => p.placement == 2);
var thirdFourth = tournament.standings.nodes.Where(p => p.placement == 3 || p.placement == 4).ToList();
var Top8 = tournament.standings.nodes.Where(p => p.placement > 4 && p.placement < 9).ToList();
var Top16 = tournament.standings.nodes.Where(p => p.placement > 8 && p.placement <= 16).ToList();
result.Results.Add(new Result(first.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name, currentRule.FirstPoint, first.placement));
lesSacs.Remove(first);
result.Results.Add(new Result(second.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name, currentRule.SecondPoint, second.placement));
lesSacs.Remove(second);
thirdFourth.ForEach(r =>
result.Results.Add(new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
thirdFourth.ForEach(p => lesSacs.Remove(p));
if (currentRule.Top8Point != 0)
{
Top8.ForEach(r =>
result.Results.Add(new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
Top8.ForEach(p => lesSacs.Remove(p));
}
if (currentRule.Top16Point != 0)
{
Top16.ForEach(r =>
result.Results.Add(
new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
Top16.ForEach(p => lesSacs.Remove(p));
}
lesSacs.ForEach(r =>
result.Results.Add(new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
} }
public Event GetBySlug(string tournamentSlug)
return await Task.FromResult(result);
}
public Task<TournamentsResult> GetSmashResult2(string tournamentSlug)
{ {
throw new NotImplementedException(); return _context.Event.Include(e => e.Tournaments).FirstOrDefault(e => e.SmashSlug == tournamentSlug);
} }
public Event GetByName(string name)
/// <summary>
/// Check if the tournament exist in database otherwise call Challonge.
/// </summary>
/// <param name="ids">tournaments ids</param>
/// <param name="games">List of known games</param>
/// <returns>List of the challonge's tournament with participents</returns>
private async Task<List<ChallongeTournament>> GetChallongeTournaments(List<int> ids, List<Game> games)
{ {
var tournaments = new List<ChallongeTournament>(); return _context.Event.Include(e=>e.Tournaments).FirstOrDefault(e => e.Name == name);
foreach (var idTournament in ids)
{
if (!TournamentExist(idTournament))
{
ChallongeTournament challongeTournament = await _challongeProvider.GetTournament(idTournament);
challongeTournament.Participents =
await _challongeProvider.GetParticipents(challongeTournament.ChallongeId);
var game = games.FirstOrDefault(g => challongeTournament.Name.Contains(g.Name));
if (game != null) challongeTournament.Game = game;
challongeTournament.Sync = DateTime.Now;
tournaments.Add(challongeTournament);
_context.ChallongeTournament.Add(challongeTournament);
_context.SaveChanges();
}
else
{
tournaments.Add(_context.ChallongeTournament.Where(e => e.ChallongeId == idTournament)
.Include(e => e.Participents).First());
} }
} }
return tournaments;
}
private bool TournamentExist(int idTournament)
{
return this._context.ChallongeTournament.Any(e => e.ChallongeId == idTournament);
}
}
} }

View File

@@ -0,0 +1,333 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LaDOSE.Business.Helper;
using LaDOSE.Business.Interface;
using LaDOSE.Entity;
using LaDOSE.Entity.Challonge;
using LaDOSE.Entity.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Result = LaDOSE.Entity.Challonge.Result;
namespace LaDOSE.Business.Service
{
public class ExternalProviderService : IExternalProviderService
{
protected LaDOSEDbContext _context;
private IChallongeProvider _challongeProvider;
private ISmashProvider _smashProvider;
#region Rules
private class Rules
{
public int PlayerMin { get; set; }
public int PlayerMax { get; set; }
public int FirstPoint { get; set; }
public int SecondPoint { get; set; }
public int ThirdFourthPoint { get; set; }
public int Top8Point { get; set; }
public int Top16Point { get; set; }
public int Participation => 1;
public Rules(int playerMin, int playerMax, int firstPoint, int secondPoint, int thirdFourthPoint,
int top8Point, int top16Point)
{
PlayerMin = playerMin;
PlayerMax = playerMax;
FirstPoint = firstPoint;
SecondPoint = secondPoint;
ThirdFourthPoint = thirdFourthPoint;
Top8Point = top8Point;
Top16Point = top16Point;
}
}
//Rules Definitions (Min Players,Max Players,First Reward,Second Reward,Third / Fourth Reward, Top 8 reward, Top 16 Reward
private List<Rules> TournamentRules = new List<Rules>()
{
new Rules(0, 8, 5, 3, 2, 0, 0),
new Rules(8, 16, 8, 5, 3, 2, 0),
new Rules(16, 32, 12, 8, 5, 3, 2),
new Rules(32, Int32.MaxValue, 18, 12, 8, 5, 3),
};
#endregion
public ExternalProviderService(LaDOSEDbContext context, IChallongeProvider challongeProvider, ISmashProvider _smashProvider)
{
this._context = context;
this._challongeProvider = challongeProvider;
this._smashProvider = _smashProvider;
}
public async Task<List<ChallongeTournament>> GetTournaments(DateTime? start, DateTime? end)
{
return await _challongeProvider.GetTournaments(start, end);
//Useless
//foreach (var tournament in tournaments)
//{
// List<ChallongeParticipent> participents = await _challongeProvider.GetParticipents(tournament.ChallongeId);
// tournament.Participents = participents;
//}
}
public async Task<TournamentsResult> GetTournamentsResult(List<int> ids)
{
TournamentsResult result = new TournamentsResult();
result.Results = new List<Result>();
var players = _context.WPUser.ToList();
var games = _context.Game.ToList();
var tournaments = await GetChallongeTournaments(ids, games);
var allParticipent = tournaments.SelectMany(e => e.Participents).Distinct((a, b) => a.Name == b.Name)
.ToList();
allParticipent.RemoveAll(e => e.Name.StartsWith("[FORFAIT]"));
//USELESS
//foreach (var participent in allParticipent)
//{
// var player = players.FirstOrDefault(e => e.Name.Contains(participent.Name));
// if (player != null)
// {
// participent.IsMember = true;
// }
//}
result.Participents = allParticipent;
foreach (var tournament in tournaments)
{
var playerCount = tournament.Participents.Count;
var lesSacs = tournament.Participents;
var currentRule = TournamentRules.FirstOrDefault(rules =>
rules.PlayerMin < playerCount && rules.PlayerMax >= playerCount
);
if (currentRule == null)
{
throw new Exception("Unable to find rules");
}
var first = tournament.Participents.First(p => p.Rank == 1);
var second = tournament.Participents.First(p => p.Rank == 2);
var thirdFourth = tournament.Participents.Where(p => p.Rank == 3 || p.Rank == 4).ToList();
var Top8 = tournament.Participents.Where(p => p.Rank > 4 && p.Rank < 9).ToList();
var Top16 = tournament.Participents.Where(p => p.Rank > 8 && p.Rank <= 16).ToList();
result.Results.Add(new Result(first.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.FirstPoint, first.Rank ?? 0));
lesSacs.Remove(first);
result.Results.Add(new Result(second.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.SecondPoint, second.Rank ?? 0));
lesSacs.Remove(second);
thirdFourth.ForEach(r =>
result.Results.Add(new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url,
currentRule.ThirdFourthPoint, r.Rank ?? 0)));
thirdFourth.ForEach(p => lesSacs.Remove(p));
if (currentRule.Top8Point != 0)
{
Top8.ForEach(r =>
result.Results.Add(new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.Top8Point, r.Rank ?? 0)));
Top8.ForEach(p => lesSacs.Remove(p));
}
if (currentRule.Top16Point != 0)
{
Top16.ForEach(r =>
result.Results.Add(
new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url, currentRule.Top16Point, r.Rank ?? 0)));
Top16.ForEach(p => lesSacs.Remove(p));
}
lesSacs.ForEach(r =>
result.Results.Add(new Result(r.Name, tournament.Game?.Id ?? 0, tournament.ChallongeId, tournament.Url,
currentRule.Participation, r.Rank ?? 0)));
}
result.Games = tournaments.Select(e => e.Game).Distinct((game, game1) => game.Name == game1.Name).Where(e => e != null).ToList();
if (result.Games == null)
{
result.Games = new List<Game>();
}
result.Games.Add(new Game() { Id = 0, Order = 9999, Name = "UNKNOW" });
return result;
}
public async Task<bool> ParseSmash(string tournamentSlug)
{
Event eventExist = GetBySlug(tournamentSlug);
if (eventExist == null)
{
var currentEvent = this._smashProvider.GetEvent(tournamentSlug).Result;
var tournaments = currentEvent.Tournaments;
var res = this._smashProvider.GetResults(ref tournaments).Result;
res = await this._smashProvider.GetSets(ref tournaments);
this._context.Add(currentEvent);
try
{
this._context.SaveChanges();
}
//POKEMON.
catch (Exception e)
{
return false;
}
return true;
}
else
{
throw new Exception("Already Exist");
}
}
private Event GetBySlug(string tournamentSlug)
{
return _context.Event.FirstOrDefault(e => e.SmashSlug == tournamentSlug);
}
public async Task<TournamentsResult> GetSmashResult(string tournamentSlug)
{
var parse = await this.ParseSmash(tournamentSlug);
var tournaments = await _smashProvider.GetTournament(tournamentSlug);
var players = tournaments.Tournament.Events.Where(e => e.standings != null).SelectMany(e => e.standings.nodes.Select(e => e.player)).ToList();
var distinctp = players.DistinctBy(e => new { e.user.id }).ToList();
var games = _context.Game.ToList();
TournamentsResult result = new TournamentsResult();
result.Results = new List<Result>();
result.Games = new List<Game>();
result.Participents = new List<ChallongeParticipent>();
distinctp.ForEach(e =>
{
var x = new ChallongeParticipent()
{
Name = e.gamerTag,
ChallongeId = e.id,
Id = e.id
};
result.Participents.Add(x);
});
games.ForEach(e =>
{
e.Id = e.SmashId ?? e.Id;
result.Games.Add(e);
});
foreach (var tournament in tournaments.Tournament.Events.Where(e => e.standings != null).ToList())
{
var playerCount = tournament.standings.nodes.Count;
var lesSacs = tournament.standings.nodes;
var currentRule = TournamentRules.FirstOrDefault(rules =>
rules.PlayerMin < playerCount && rules.PlayerMax >= playerCount
);
if (currentRule == null)
{
throw new Exception("Unable to find rules");
}
var first = tournament.standings.nodes.First(p => p.placement == 1);
var second = tournament.standings.nodes.First(p => p.placement == 2);
var thirdFourth = tournament.standings.nodes.Where(p => p.placement == 3 || p.placement == 4).ToList();
var Top8 = tournament.standings.nodes.Where(p => p.placement > 4 && p.placement < 9).ToList();
var Top16 = tournament.standings.nodes.Where(p => p.placement > 8 && p.placement <= 16).ToList();
result.Results.Add(new Result(first.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name, currentRule.FirstPoint, first.placement));
lesSacs.Remove(first);
result.Results.Add(new Result(second.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name, currentRule.SecondPoint, second.placement));
lesSacs.Remove(second);
thirdFourth.ForEach(r =>
result.Results.Add(new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
thirdFourth.ForEach(p => lesSacs.Remove(p));
if (currentRule.Top8Point != 0)
{
Top8.ForEach(r =>
result.Results.Add(new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
Top8.ForEach(p => lesSacs.Remove(p));
}
if (currentRule.Top16Point != 0)
{
Top16.ForEach(r =>
result.Results.Add(
new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
Top16.ForEach(p => lesSacs.Remove(p));
}
lesSacs.ForEach(r =>
result.Results.Add(new Result(r.player.gamerTag, tournament.videogame.id, tournament.id, tournament.name,
currentRule.ThirdFourthPoint, r.placement)));
}
return await Task.FromResult(result);
}
public Task<TournamentsResult> GetSmashResult2(string tournamentSlug)
{
throw new NotImplementedException();
}
public async Task<List<Event>> GetChallongeEvents(List<int> ids)
{
var events = await this._challongeProvider.GetEvents(ids);
this._context.Event.AddRange(events);
return events;
}
/// <summary>
/// Check if the tournament exist in database otherwise call Challonge.
/// </summary>
/// <param name="ids">tournaments ids</param>
/// <param name="games">List of known games</param>
/// <returns>List of the challonge's tournament with participents</returns>
private async Task<List<ChallongeTournament>> GetChallongeTournaments(List<int> ids, List<Game> games)
{
var tournaments = new List<ChallongeTournament>();
foreach (var idTournament in ids)
{
if (!TournamentExist(idTournament))
{
ChallongeTournament challongeTournament = await _challongeProvider.GetTournament(idTournament);
challongeTournament.Participents =
await _challongeProvider.GetParticipents(challongeTournament.ChallongeId);
var game = games.FirstOrDefault(g => challongeTournament.Name.Contains(g.Name));
if (game != null) challongeTournament.Game = game;
challongeTournament.Sync = DateTime.Now;
tournaments.Add(challongeTournament);
_context.ChallongeTournament.Add(challongeTournament);
_context.SaveChanges();
}
else
{
tournaments.Add(_context.ChallongeTournament.Where(e => e.ChallongeId == idTournament)
.Include(e => e.Participents).First());
}
}
return tournaments;
}
private bool TournamentExist(int idTournament)
{
return this._context.ChallongeTournament.Any(e => e.ChallongeId == idTournament);
}
}
}

View File

@@ -25,6 +25,11 @@ namespace LaDOSE.Business.Service
return base.AddOrUpdate(entity); return base.AddOrUpdate(entity);
} }
public int? GetIdByName(string name)
{
return _context.Game.FirstOrDefault(e => e.Name == name)?.Id ?? null;
}
public override IEnumerable<Game> GetAll() public override IEnumerable<Game> GetAll()
{ {
return _context.Game.ToList(); return _context.Game.ToList();

View File

@@ -2,6 +2,7 @@
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.Business.Provider.SmashProvider; using LaDOSE.Business.Provider.SmashProvider;
using LaDOSE.Entity; using LaDOSE.Entity;
using LaDOSE.Entity.Challonge;
using LaDOSE.Entity.Context; using LaDOSE.Entity.Context;
using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Internal;
@@ -14,7 +15,7 @@ namespace LaDOSE.Business.Service
{ {
} }
public int GetBySmash(ParticipantType participantUser) public int GetIdBySmash(ParticipantType participantUser)
{ {
//var p2 = _context.Player.ToList(); //var p2 = _context.Player.ToList();
@@ -41,5 +42,29 @@ namespace LaDOSE.Business.Service
return p.Id; return p.Id;
} }
public int GetIdByName(ChallongeParticipent challongeParticipent)
{
if (string.IsNullOrEmpty(challongeParticipent.Name))
{
challongeParticipent.Name = "UNKNOWPLAYER";
}
var p = _context.Player.FirstOrDefault(e => e.Gamertag == challongeParticipent.Name);
if (p == null)
{
var entity = new Player()
{
Gamertag = challongeParticipent.Name,
Name = challongeParticipent.Name,
ChallongeId = challongeParticipent.ChallongeId,
};
_context.Player.Add(entity);
_context.SaveChanges();
return entity.Id;
}
return p.Id;
}
} }
} }