Test Connection

Add Todo
Bot use Webservice now
TBD : Rework Event
This commit is contained in:
2019-03-27 00:37:11 +01:00
parent 74327eb381
commit 63db02d798
25 changed files with 379 additions and 178 deletions

View File

@@ -0,0 +1,22 @@
using LaDOSE.Business.Interface;
using LaDOSE.DTO;
using LaDOSE.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LaDOSE.Api.Controllers
{
[Authorize]
[Route("api/[controller]")]
[Produces("application/json")]
public class TodoController : GenericControllerDTO<ITodoService, Todo, TodoDTO>
{
public TodoController(ITodoService service) : base(service)
{
}
}
}

View File

@@ -6,6 +6,7 @@ using System.Security.Claims;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.DTO;
using LaDOSE.Entity; using LaDOSE.Entity;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -50,20 +51,21 @@ namespace LaDOSE.Api.Controllers
{ {
new Claim(ClaimTypes.Name, user.Id.ToString()) new Claim(ClaimTypes.Name, user.Id.ToString())
}), }),
Expires = DateTime.UtcNow.AddDays(7), Expires = DateTime.UtcNow.AddMinutes(16),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
}; };
var token = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token); var tokenString = tokenHandler.WriteToken(token);
// return basic user info (without password) and token to store client side // return basic user info (without password) and token to store client side
return Ok(new return Ok(new ApplicationUserDTO
{ {
Id = user.Id, Id = user.Id,
Username = user.Username, Username = user.Username,
FirstName = user.FirstName, FirstName = user.FirstName,
LastName = user.LastName, LastName = user.LastName,
Token = tokenString Token = tokenString,
Expire = token.ValidTo
}); });
} }

View File

@@ -96,6 +96,7 @@ namespace LaDOSE.Api
// return unauthorized if user no longer exists // return unauthorized if user no longer exists
context.Fail("Unauthorized"); context.Fail("Unauthorized");
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
}; };
@@ -117,9 +118,10 @@ namespace LaDOSE.Api
cfg.CreateMap<WPUser, LaDOSE.DTO.WPUserDTO>(); cfg.CreateMap<WPUser, LaDOSE.DTO.WPUserDTO>();
cfg.CreateMap<WPUser, LaDOSE.DTO.WPUserDTO>(); cfg.CreateMap<WPUser, LaDOSE.DTO.WPUserDTO>();
cfg.CreateMap<WPEvent, LaDOSE.DTO.WPEventDTO>(); cfg.CreateMap<WPEvent, LaDOSE.DTO.WPEventDTO>();
cfg.CreateMap<ApplicationUser, LaDOSE.DTO.ApplicationUser>(); cfg.CreateMap<ApplicationUser, LaDOSE.DTO.ApplicationUserDTO>();
cfg.CreateMap<WPBooking, LaDOSE.DTO.WPBookingDTO>().ForMember(e=>e.Meta,opt=>opt.MapFrom(s=>s.Meta.CleanWpMeta())); cfg.CreateMap<WPBooking, LaDOSE.DTO.WPBookingDTO>().ForMember(e=>e.Meta,opt=>opt.MapFrom(s=>s.Meta.CleanWpMeta()));
cfg.CreateMapTwoWay<Game, LaDOSE.DTO.GameDTO>(); cfg.CreateMapTwoWay<Game, LaDOSE.DTO.GameDTO>();
cfg.CreateMapTwoWay<Todo, LaDOSE.DTO.TodoDTO>();
}); });
} }
@@ -133,6 +135,7 @@ namespace LaDOSE.Api
services.AddScoped<IEventService, EventService>(); services.AddScoped<IEventService, EventService>();
services.AddScoped<ISeasonService, SeasonService>(); services.AddScoped<ISeasonService, SeasonService>();
services.AddScoped<IWordPressService, WordPressService>(); services.AddScoped<IWordPressService, WordPressService>();
services.AddScoped<ITodoService, TodoService>();
} }

View File

@@ -1,7 +1,9 @@
 
using System;
namespace LaDOSE.DTO namespace LaDOSE.DTO
{ {
public class ApplicationUser public class ApplicationUserDTO
{ {
public int Id { get; set; } public int Id { get; set; }
public string FirstName { get; set; } public string FirstName { get; set; }
@@ -10,6 +12,7 @@ namespace LaDOSE.DTO
public string Password { get; set; } public string Password { get; set; }
public string Token { get; set; } public string Token { get; set; }
public DateTime Expire { get; set; }
} }
} }

View File

@@ -0,0 +1,15 @@
using System;
namespace LaDOSE.DTO
{
public class TodoDTO
{
public int Id { get; set; }
public string User { get; set; }
public string Task { get; set; }
public bool Done { get; set; }
public DateTime Created { get; set; }
public DateTime? Deleted { get; set; }
}
}

View File

@@ -4,28 +4,40 @@ using System.Windows;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using Caliburn.Micro; using Caliburn.Micro;
using LaDOSE.REST; using LaDOSE.REST;
using LaDOSE.REST.Event;
namespace LaDOSE.DesktopApp.ViewModels namespace LaDOSE.DesktopApp.ViewModels
{ {
public class ShellViewModel : Conductor<IScreen>.Collection.AllActive public class ShellViewModel : Conductor<IScreen>.Collection.AllActive
{ {
private string _user;
public string User
{
get => _user;
set
{
_user = value;
NotifyOfPropertyChange(User);
}
}
protected override void OnInitialize() protected override void OnInitialize()
{ {
this.DisplayName = "LaDOSE"; this.DisplayName = "LaDOSE";
this.User = "Test";
this.AppIcon = BitmapFrame.Create(Application.GetResourceStream(new Uri("/LaDOSE.DesktopApp;component/Resources/64x64.png", this.AppIcon = BitmapFrame.Create(Application.GetResourceStream(new Uri("/LaDOSE.DesktopApp;component/Resources/64x64.png",
UriKind.RelativeOrAbsolute)).Stream); UriKind.RelativeOrAbsolute)).Stream);
var appSettings = ConfigurationManager.AppSettings; var appSettings = ConfigurationManager.AppSettings;
string url = (string)appSettings["ApiUri"]; string url = (string)appSettings["ApiUri"];
string user = (string)appSettings["ApiUser"]; string user = (string)appSettings["ApiUser"];
string password = (string)appSettings["ApiPassword"]; string password = (string)appSettings["ApiPassword"];
Uri uri = new Uri(url); Uri uri = new Uri(url);
var restService = IoC.Get<RestService>(); var restService = IoC.Get<RestService>();
restService.UpdatedJwtEvent += TokenUpdate;
restService.Connect(uri, user, password); restService.Connect(uri, user, password);
var wordPressViewModel = new WordPressViewModel(IoC.Get<RestService>()); var wordPressViewModel = new WordPressViewModel(IoC.Get<RestService>());
ActivateItem(wordPressViewModel); ActivateItem(wordPressViewModel);
base.OnInitialize(); base.OnInitialize();
@@ -33,6 +45,12 @@ namespace LaDOSE.DesktopApp.ViewModels
} }
private void TokenUpdate(object sender, UpdatedJwtEventHandler e)
{
this.User = e.Message.FirstName;
}
public BitmapFrame AppIcon { get; set; } public BitmapFrame AppIcon { get; set; }
public void LoadEvent() public void LoadEvent()

View File

@@ -72,8 +72,10 @@
</TabControl.ItemTemplate> </TabControl.ItemTemplate>
</TabControl> </TabControl>
<StatusBar Grid.Row="2"> <StatusBar Grid.Row="2">
<StackPanel Orientation="Horizontal">
<TextBlock> User : </TextBlock>
<TextBlock Margin="5,0,0,0" Text="{Binding Path=User,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</StackPanel>
</StatusBar> </StatusBar>
</Grid> </Grid>

View File

@@ -14,18 +14,18 @@ namespace LaDOSE.DiscordBot.Command
} }
[RequireRolesAttribute("Staff")] //[RequireRolesAttribute("Staff")]
[Command("update")] //[Command("update")]
public async Task UpdateAsync(CommandContext ctx) //public async Task UpdateAsync(CommandContext ctx)
{ //{
var tournament = await dep.ChallongeService.GetLastTournament(); // //var tournament = await dep.ChallongeService.GetLastTournament();
await ctx.RespondAsync($"Mise à jour effectuée"); // //await ctx.RespondAsync($"Mise à jour effectuée");
} //}
[Command("last")] [Command("last")]
public async Task LastAsync(CommandContext ctx) public async Task LastAsync(CommandContext ctx)
{ {
var lastTournamentMessage = dep.ChallongeService.GetLastTournamentMessage(); var lastTournamentMessage = dep.WebService.GetLastChallonge();
await ctx.RespondAsync(lastTournamentMessage); await ctx.RespondAsync(lastTournamentMessage);
} }

View File

@@ -1,6 +1,9 @@
using System.Threading.Tasks; using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Interactivity;
using LaDOSE.DTO;
namespace LaDOSE.DiscordBot.Command namespace LaDOSE.DiscordBot.Command
{ {
@@ -17,22 +20,98 @@ namespace LaDOSE.DiscordBot.Command
public async Task TodoAsync(CommandContext ctx, string command,params string[] todo) public async Task TodoAsync(CommandContext ctx, string command,params string[] todo)
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
string args = string.Join(" ",todo);
switch (command.ToUpperInvariant()) switch (command.ToUpperInvariant())
{ {
case "ADD": case "ADD":
dep.TodoService.Add(todo[0]);
var todoDto = new TodoDTO
{
Created = DateTime.Now,
Done = false,
Deleted = null,
Task = args,
User = ctx.User.Username,
};
dep.WebService.RestService.UpdateTodo(todoDto);
//dep.WebService.RestService.UpdateGame();
break; break;
case "LIST": case "LIST":
await ctx.RespondAsync($"{dep.TodoService.List()}"); var todoDtos = dep.WebService.RestService.GetTodos();
foreach (var task in todoDtos)
{
string taskStatus = task.Done ? ":white_check_mark:" : ":negative_squared_cross_mark:";
await ctx.RespondAsync($"{task?.Id} - {task?.Task} Par : {task?.User} Etat : {taskStatus}");
}
break; break;
case "DEL": case "DEL":
int id; try
if (int.TryParse(todo[0], out id))
{ {
await ctx.RespondAsync($"{dep.TodoService.Delete(id)}"); int id = int.Parse(todo[0]);
await ctx.RespondAsync(dep.WebService.RestService.DeleteTodo(id) ? $"Deleted" : $"Error");
}
catch (Exception e)
{
await ctx.RespondAsync($"Error {e.Message}");
return;
}
break; break;
}; case "V":
await ctx.RespondAsync($"invalid id"); try
{
int id = int.Parse(todo[0]);
var todoById = dep.WebService.RestService.GetTodoById(id);
todoById.Done = true;
dep.WebService.RestService.UpdateTodo(todoById);
await ctx.RespondAsync($"Done : {todoById.Id} - {todoById.Task}");
}
catch (Exception e)
{
await ctx.RespondAsync($"Error {e.Message}");
return;
}
break;
case "X":
try
{
int id = int.Parse(todo[0]);
var todoById = dep.WebService.RestService.GetTodoById(id);
todoById.Done = false;
dep.WebService.RestService.UpdateTodo(todoById);
await ctx.RespondAsync($"Undone : {todoById.Id} - {todoById.Task}");
}
catch (Exception e)
{
await ctx.RespondAsync($"Erreur {e.Message}");
return;
}
break;
case "TRUNC":
try
{
var todos = dep.WebService.RestService.GetTodos();
await ctx.RespondAsync($"Sure ? (Y/N)");
var interactivity = ctx.Client.GetInteractivityModule();
var waitForMessageAsync = await interactivity.WaitForMessageAsync(xm => xm.Content.Contains("Y")||xm.Content.Contains("N"), TimeSpan.FromSeconds(10));
if (waitForMessageAsync!= null)
{
if (waitForMessageAsync.Message.Content == "Y")
{
foreach (var task in todos)
{
dep.WebService.RestService.DeleteTodo(task.Id);
await ctx.RespondAsync($"Deleted - {task.Id}");
}
}
}
}
catch (Exception e)
{
await ctx.RespondAsync($"Erreur {e.Message}");
return;
}
break; break;
} }

View File

@@ -8,8 +8,6 @@ namespace LaDOSE.DiscordBot
{ {
internal InteractivityModule Interactivity { get; set; } internal InteractivityModule Interactivity { get; set; }
internal CancellationTokenSource Cts { get; set; } internal CancellationTokenSource Cts { get; set; }
public ChallongeService ChallongeService { get; set; }
public TodoService TodoService { get; set; }
public WebService WebService { get; set; } public WebService WebService { get; set; }
} }
} }

View File

@@ -16,7 +16,7 @@ namespace LaDOSE.DiscordBot
class Program class Program
{ {
static DiscordClient discord; static DiscordClient discord;
static InteractivityModule Interactivity { get; set; }
static void Main(string[] args) static void Main(string[] args)
{ {
MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult(); MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult();
@@ -44,9 +44,20 @@ namespace LaDOSE.DiscordBot
TokenType = TokenType.Bot TokenType = TokenType.Bot
}); });
discord.UseInteractivity(new InteractivityConfiguration
{
// default pagination behaviour to just ignore the reactions
PaginationBehaviour = TimeoutBehaviour.Ignore,
// default pagination timeout to 5 minutes
PaginationTimeout = TimeSpan.FromMinutes(5),
// default timeout for other actions to 2 minutes
Timeout = TimeSpan.FromMinutes(2)
});
var webService = new WebService(new Uri(restUrl),restUser,restPassword); var webService = new WebService(new Uri(restUrl),restUser,restPassword);
var challongeService = new ChallongeService(challongeToken); //var challongeService = new ChallongeService(challongeToken);
var todoService = new TodoService();
var cts = new CancellationTokenSource(); var cts = new CancellationTokenSource();
DependencyCollection dep = null; DependencyCollection dep = null;
@@ -54,10 +65,8 @@ namespace LaDOSE.DiscordBot
{ {
d.AddInstance(new Dependencies() d.AddInstance(new Dependencies()
{ {
Cts = cts, Cts = cts,
ChallongeService = challongeService, //ChallongeService = challongeService,
TodoService = todoService,
WebService = webService WebService = webService
}); });
dep = d.Build(); dep = d.Build();

View File

@@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChallongeCSharpDriver;
using ChallongeCSharpDriver.Caller;
using ChallongeCSharpDriver.Core.Queries;
using ChallongeCSharpDriver.Core.Results;
using ChallongeCSharpDriver.Main;
using ChallongeCSharpDriver.Main.Objects;
namespace LaDOSE.DiscordBot.Service
{
public class ChallongeService
{
private ChallongeConfig Config;
public string ApiKey { get; set; }
public ChallongeHTTPClientAPICaller ApiCaller { get; set; }
public string DernierTournois { get; set; }
public ChallongeService(string apiKey)
{
this.ApiKey = apiKey;
this.Config = new ChallongeConfig(this.ApiKey);
this.ApiCaller = new ChallongeHTTPClientAPICaller(Config);
DernierTournois = "Aucun tournois.";
}
public async Task<Boolean> GetLastTournament()
{
try
{
List<TournamentResult> tournamentResultList = await new TournamentsQuery()
{
state = TournamentState.Ended
}
.call(this.ApiCaller);
var lastDate = tournamentResultList.Max(e => e.completed_at);
if (lastDate.HasValue)
{
var lastRankingDate = new DateTime(lastDate.Value.Year, lastDate.Value.Month, lastDate.Value.Day);
var lastTournament = tournamentResultList.Where(e => e.completed_at > lastRankingDate).ToList();
string returnValue = "Les derniers tournois : \n";
foreach (var tournamentResult in lastTournament)
{
returnValue += $"{tournamentResult.name} : <https://challonge.com/{tournamentResult.url}> \n";
}
DernierTournois = returnValue;
}
return true;
}
catch
{
return false;
}
}
public string GetLastTournamentMessage()
{
return DernierTournois;
}
}
}

View File

@@ -1,61 +0,0 @@
using System;
using System.IO;
namespace LaDOSE.DiscordBot.Service
{
public class TodoService
{
private const string db = "todo.txt";
public TodoService()
{
}
public bool Add(string text)
{
if (!string.IsNullOrEmpty(text)) {
using (var textWriter =File.AppendText(db))
{
textWriter.WriteLine(text);
}
return true;
}
return false;
}
public bool Delete(int id)
{
string returnText = "";
var text = File.ReadAllText(db);
var i = 0;
foreach (var line in text.Split('\n'))
{
++i;
if (i != id)
{
returnText += $"{line}\n";
}
}
File.WriteAllText(db,returnText);
return true;
}
public string List()
{
string returnText = "";
var text = File.ReadAllText(db);
var i = 0;
foreach (var line in text.Split())
{
if(!string.IsNullOrEmpty(line))
returnText += $"{++i}. {line}";
}
return returnText;
}
}
}

View File

@@ -10,6 +10,7 @@ using ChallongeCSharpDriver.Main;
using ChallongeCSharpDriver.Main.Objects; using ChallongeCSharpDriver.Main.Objects;
using LaDOSE.DTO; using LaDOSE.DTO;
using LaDOSE.REST; using LaDOSE.REST;
using RestSharp.Authenticators;
namespace LaDOSE.DiscordBot.Service namespace LaDOSE.DiscordBot.Service
{ {
@@ -17,12 +18,20 @@ namespace LaDOSE.DiscordBot.Service
{ {
private RestService restService; private RestService restService;
public RestService RestService => restService;
public WebService(Uri uri,string user,string password) public WebService(Uri uri,string user,string password)
{ {
restService = new RestService(); restService = new RestService();
restService.Connect(uri,user,password); restService.Connect(uri,user,password);
} }
private void CheckToken()
{
}
public String GetInscrits() public String GetInscrits()
@@ -37,5 +46,10 @@ namespace LaDOSE.DiscordBot.Service
{ {
return restService.RefreshDb(); return restService.RefreshDb();
} }
public string GetLastChallonge()
{
return restService.GetLastChallonge();
}
} }
} }

View File

@@ -9,6 +9,7 @@ namespace LaDOSE.Entity.Context
public DbSet<ApplicationUser> ApplicationUser { get; set; } public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<Season> Season { get; set; } public DbSet<Season> Season { get; set; }
public DbSet<Event> Event { get; set; } public DbSet<Event> Event { get; set; }
public DbSet<Todo> Todo { get; set; }
#region WordPress #region WordPress
public DbSet<WPUser> WPUser { get; set; } public DbSet<WPUser> WPUser { get; set; }

View File

@@ -1,5 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace LaDOSE.Entity namespace LaDOSE.Entity

View File

@@ -0,0 +1,14 @@
using System;
namespace LaDOSE.Entity
{
public class Todo : Context.Entity
{
public string User { get; set; }
public string Task { get; set; }
public bool Done { get; set; }
public DateTime Created { get; set; }
public DateTime? Deleted { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
using System;
using LaDOSE.DTO;
namespace LaDOSE.REST.Event
{
public class UpdatedJwtEventHandler : EventArgs
{
private ApplicationUserDTO msg;
public UpdatedJwtEventHandler(ApplicationUserDTO applicationUser)
{
this.msg = applicationUser;
}
public ApplicationUserDTO Message => msg;
}
}

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using LaDOSE.DTO; using LaDOSE.DTO;
using LaDOSE.REST.Event;
using RestSharp; using RestSharp;
using RestSharp.Authenticators; using RestSharp.Authenticators;
using RestSharp.Serialization.Json; using RestSharp.Serialization.Json;
@@ -9,23 +10,43 @@ namespace LaDOSE.REST
{ {
public class RestService public class RestService
{ {
private string username { get; set; }
private string password { get; set; }
private ApplicationUserDTO Auth { get; set; }
public string UserName => Auth?.FirstName;
public DateTime ValidUntil => Auth.Expire;
//private ApplicationUserDTO token = null;
public RestClient Client { get; set; } public RestClient Client { get; set; }
public event EventHandler<UpdatedJwtEventHandler> UpdatedJwtEvent;
public RestService() { } public RestService() { }
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);
this.username = user;
this.password = password;
GetToken(user, password);
}
private void GetToken(string user, string password)
{
var restRequest = new RestRequest("users/auth", Method.POST); var restRequest = new RestRequest("users/auth", Method.POST);
restRequest.AddJsonBody(new {username = user, password = password}); restRequest.AddJsonBody(new {username = user, password = password});
var response = Client.Post(restRequest); var response = Client.Post(restRequest);
if (response.IsSuccessful) if (response.IsSuccessful)
{ {
JsonDeserializer d = new JsonDeserializer(); JsonDeserializer d = new JsonDeserializer();
var applicationUser = d.Deserialize<ApplicationUser>(response); var applicationUser = d.Deserialize<ApplicationUserDTO>(response);
this.Auth = applicationUser;
Client.Authenticator = new JwtAuthenticator($"{applicationUser.Token}"); Client.Authenticator = new JwtAuthenticator($"{applicationUser.Token}");
RaiseUpdatedJwtEvent(new UpdatedJwtEventHandler(this.Auth));
} }
else else
{ {
@@ -33,6 +54,23 @@ namespace LaDOSE.REST
} }
} }
private void RaiseUpdatedJwtEvent(UpdatedJwtEventHandler auth)
{
EventHandler<UpdatedJwtEventHandler> handler = UpdatedJwtEvent;
handler?.Invoke(this, auth);
}
private void CheckToken()
{
if (this.Auth.Expire <= DateTime.Now)
{
GetToken(this.username,this.password);
}
}
#region PostFix #region PostFix
private T Post<T>(string resource,T entity) private T Post<T>(string resource,T entity)
@@ -91,32 +129,43 @@ namespace LaDOSE.REST
#region WordPress #region WordPress
public List<WPEventDTO> GetEvents() public List<WPEventDTO> GetEvents()
{ {
CheckToken();
var restRequest = new RestRequest("/api/wordpress/WPEvent", Method.GET); var restRequest = new RestRequest("/api/wordpress/WPEvent", Method.GET);
var restResponse = Client.Get<List<WPEventDTO>>(restRequest); var restResponse = Client.Get<List<WPEventDTO>>(restRequest);
return restResponse.Data; return restResponse.Data;
} }
public WPEventDTO GetNextEvent() public WPEventDTO GetNextEvent()
{ {
CheckToken();
var restRequest = new RestRequest("/api/wordpress/NextEvent", Method.GET); var restRequest = new RestRequest("/api/wordpress/NextEvent", Method.GET);
var restResponse = Client.Get<WPEventDTO>(restRequest); var restResponse = Client.Get<WPEventDTO>(restRequest);
return restResponse.Data; return restResponse.Data;
} }
public string GetLastChallonge()
{
CheckToken();
var restRequest = new RestRequest($"/api/wordpress/GetLastChallonge/", Method.GET);
var restResponse = Client.Get(restRequest);
return restResponse.Content;
}
public string CreateChallonge(int gameId, int eventId) public string CreateChallonge(int gameId, int eventId)
{ {
CheckToken();
var restRequest = new RestRequest($"/api/wordpress/CreateChallonge/{gameId}/{eventId}", Method.GET); var restRequest = new RestRequest($"/api/wordpress/CreateChallonge/{gameId}/{eventId}", Method.GET);
var restResponse = Client.Get(restRequest); var restResponse = Client.Get(restRequest);
return restResponse.Content; return restResponse.Content;
} }
public string CreateChallonge2(int gameId, int eventId, List<WPUserDTO> optionalPlayers) public string CreateChallonge2(int gameId, int eventId, List<WPUserDTO> optionalPlayers)
{ {
CheckToken();
var restResponse = Post<List<WPUserDTO>,string>($"/api/wordpress/CreateChallonge/{gameId}/{eventId}",optionalPlayers); var restResponse = Post<List<WPUserDTO>,string>($"/api/wordpress/CreateChallonge/{gameId}/{eventId}",optionalPlayers);
return restResponse; return restResponse;
} }
public bool RefreshDb() public bool RefreshDb()
{ {
CheckToken();
var restRequest = new RestRequest("/api/Wordpress/UpdateDb", Method.GET); var restRequest = new RestRequest("/api/Wordpress/UpdateDb", Method.GET);
var restResponse = Client.Get<bool>(restRequest); var restResponse = Client.Get<bool>(restRequest);
return restResponse.Data; return restResponse.Data;
@@ -124,6 +173,7 @@ namespace LaDOSE.REST
public List<WPUserDTO> GetUsers(int wpEventId, int gameId) public List<WPUserDTO> GetUsers(int wpEventId, int gameId)
{ {
CheckToken();
var restRequest = new RestRequest($"/api/Wordpress/GetUsers/{wpEventId}/{gameId}", Method.GET); var restRequest = new RestRequest($"/api/Wordpress/GetUsers/{wpEventId}/{gameId}", Method.GET);
var restResponse = Client.Get<List<WPUserDTO>>(restRequest); var restResponse = Client.Get<List<WPUserDTO>>(restRequest);
return restResponse.Data; return restResponse.Data;
@@ -131,6 +181,7 @@ namespace LaDOSE.REST
public List<WPUserDTO> GetUsersOptions(int wpEventId, int gameId) public List<WPUserDTO> GetUsersOptions(int wpEventId, int gameId)
{ {
CheckToken();
var restRequest = new RestRequest($"/api/Wordpress/GetUsersOptions/{wpEventId}/{gameId}", Method.GET); var restRequest = new RestRequest($"/api/Wordpress/GetUsersOptions/{wpEventId}/{gameId}", Method.GET);
var restResponse = Client.Get<List<WPUserDTO>>(restRequest); var restResponse = Client.Get<List<WPUserDTO>>(restRequest);
return restResponse.Data; return restResponse.Data;
@@ -142,6 +193,7 @@ namespace LaDOSE.REST
#region Games #region Games
public List<GameDTO> GetGames() public List<GameDTO> GetGames()
{ {
CheckToken();
var restRequest = new RestRequest("/api/Game", Method.GET); var restRequest = new RestRequest("/api/Game", Method.GET);
var restResponse = Client.Get<List<GameDTO>>(restRequest); var restResponse = Client.Get<List<GameDTO>>(restRequest);
return restResponse.Data; return restResponse.Data;
@@ -149,10 +201,12 @@ namespace LaDOSE.REST
public GameDTO UpdateGame(GameDTO game) public GameDTO UpdateGame(GameDTO game)
{ {
CheckToken();
return Post("Api/Game", game); return Post("Api/Game", game);
} }
public bool DeleteGame(int gameId) public bool DeleteGame(int gameId)
{ {
CheckToken();
var restRequest = new RestRequest($"/api/Game/{gameId}", Method.DELETE); var restRequest = new RestRequest($"/api/Game/{gameId}", Method.DELETE);
var restResponse = Client.Execute(restRequest); var restResponse = Client.Execute(restRequest);
return restResponse.IsSuccessful; return restResponse.IsSuccessful;
@@ -164,7 +218,37 @@ namespace LaDOSE.REST
#endregion #endregion
#region Todo
public List<TodoDTO> GetTodos()
{
CheckToken();
var restRequest = new RestRequest("/api/Todo", Method.GET);
var restResponse = Client.Get<List<TodoDTO>>(restRequest);
return restResponse.Data;
}
public TodoDTO GetTodoById(int id)
{
CheckToken();
var restRequest = new RestRequest($"/api/Todo/{id}", Method.GET);
var restResponse = Client.Get<TodoDTO>(restRequest);
return restResponse.Data;
}
public TodoDTO UpdateTodo(TodoDTO Todo)
{
CheckToken();
return Post("Api/Todo", Todo);
}
public bool DeleteTodo(int todoId)
{
CheckToken();
var restRequest = new RestRequest($"/api/Todo/{todoId}", Method.DELETE);
var restResponse = Client.Execute(restRequest);
return restResponse.IsSuccessful;
}
#endregion

View File

@@ -6,7 +6,7 @@ namespace LaDOSE.Business.Interface
{ {
public interface IChallongeProvider public interface IChallongeProvider
{ {
Task<Boolean> GetLastTournament(); Task<string> GetLastTournament();
string GetLastTournamentMessage(); string GetLastTournamentMessage();
Task<TournamentResult> CreateTournament(string name, string url); Task<TournamentResult> CreateTournament(string name, string url);
Task<ParticipantResult> AddPlayer(int tournamentId, string userName); Task<ParticipantResult> AddPlayer(int tournamentId, string userName);

View File

@@ -0,0 +1,9 @@
using LaDOSE.Entity;
namespace LaDOSE.Business.Interface
{
public interface ITodoService : IBaseService<Todo>
{
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using LaDOSE.Entity; using LaDOSE.Entity;
using LaDOSE.Entity.Wordpress; using LaDOSE.Entity.Wordpress;
@@ -12,5 +13,7 @@ namespace LaDOSE.Business.Interface
List<WPUser> GetBookingOptions(int wpEventId, Game game); List<WPUser> GetBookingOptions(int wpEventId, Game game);
bool UpdateBooking(); bool UpdateBooking();
string CreateChallonge(int gameId, int wpEventId, IList<WPUser> additionPlayers); string CreateChallonge(int gameId, int wpEventId, IList<WPUser> additionPlayers);
Task<string> GetLastChallonge();
} }
} }

View File

@@ -45,8 +45,9 @@ namespace LaDOSE.Business.Provider
} }
public async Task<Boolean> GetLastTournament() public async Task<string> GetLastTournament()
{ {
string dernierTournois = null;
try try
{ {
@@ -59,6 +60,7 @@ namespace LaDOSE.Business.Provider
var lastDate = tournamentResultList.Max(e => e.completed_at); var lastDate = tournamentResultList.Max(e => e.completed_at);
if (lastDate.HasValue) if (lastDate.HasValue)
{ {
var lastRankingDate = new DateTime(lastDate.Value.Year, lastDate.Value.Month, lastDate.Value.Day); var lastRankingDate = new DateTime(lastDate.Value.Year, lastDate.Value.Month, lastDate.Value.Day);
@@ -70,13 +72,13 @@ namespace LaDOSE.Business.Provider
returnValue += $"{tournamentResult.name} : <https://challonge.com/{tournamentResult.url}> \n"; returnValue += $"{tournamentResult.name} : <https://challonge.com/{tournamentResult.url}> \n";
} }
DernierTournois = returnValue; dernierTournois = returnValue;
} }
return true; return dernierTournois;
} }
catch catch
{ {
return false; return dernierTournois;
} }
} }
public string GetLastTournamentMessage() public string GetLastTournamentMessage()

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using LaDOSE.Business.Interface;
using LaDOSE.Entity;
using LaDOSE.Entity.Context;
using Microsoft.EntityFrameworkCore;
namespace LaDOSE.Business.Service
{
public class TodoService : BaseService<Todo>, ITodoService
{
public TodoService(LaDOSEDbContext context) : base(context)
{
}
public override bool Delete(int id)
{
var find = _context.Find<Todo>(id);
find.Deleted = DateTime.Now;
this._context.SaveChanges();
return _context.Entry(find).State == EntityState.Modified;
}
public override IEnumerable<Todo> GetAll()
{
return _context.Set<Todo>().Where(e=>e.Deleted == null).ToList();
}
}
}

View File

@@ -1,7 +1,12 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using ChallongeCSharpDriver;
using ChallongeCSharpDriver.Core.Queries;
using ChallongeCSharpDriver.Core.Results;
using LaDOSE.Business.Helper; using LaDOSE.Business.Helper;
using LaDOSE.Business.Interface; using LaDOSE.Business.Interface;
using LaDOSE.Entity; using LaDOSE.Entity;
@@ -154,6 +159,12 @@ namespace LaDOSE.Business.Service
return "error while creating challonge"; return "error while creating challonge";
} }
public async Task<string> GetLastChallonge()
{
var lastTournament = await _challongeProvider.GetLastTournament();
return lastTournament;
}
private string FormatCurrentEventName(string currentEventName) private string FormatCurrentEventName(string currentEventName)
{ {