public Playoff(CompetitionConfig competitionConfig, string name, int year, int currentRound, List <PlayoffSeries> series, List <CompetitionTeam> teams, Schedule schedule, IList <TeamRanking> rankings, bool started, bool finished, int?startDay, int?endDay) : base(competitionConfig, name, year, schedule, rankings, teams, started, finished, startDay, endDay) { Series = series; Teams = teams; CurrentRound = currentRound; }
public void RunClear(ShardedCommandContext context) { var guildIds = context.Client.Guilds.Select(x => x.Id).ToArray(); var removePlayers = currentDatabase.Query <Player>(x => !guildIds.Contains(x.GuildId)); var removeLobbies = currentDatabase.Query <Lobby>(x => !guildIds.Contains(x.GuildId)); var removeGuilds = currentDatabase.Query <CompetitionConfig>(x => !guildIds.Contains(x.GuildId)); var removeGames = currentDatabase.Query <GameResult>(x => x.LegacyGame); foreach (var player in removePlayers) { currentDatabase.Remove <Player>(Player.DocumentName(player.GuildId, player.UserId)); } foreach (var lobby in removeLobbies) { currentDatabase.Remove <Lobby>(Lobby.DocumentName(lobby.GuildId, lobby.ChannelId)); } foreach (var guild in removeGuilds) { currentDatabase.Remove <CompetitionConfig>(CompetitionConfig.DocumentName(guild.GuildId)); } foreach (var game in removeGames) { currentDatabase.Remove <GameResult>(GameResult.DocumentName(game.GameId, game.LobbyId, game.GuildId)); } }
private CompetitionConfig CreateCompetition(ulong guildId) { var config = new CompetitionConfig(guildId); SaveCompetition(config); return(config); }
//maybe move to a different sevice method public bool IsCompetitionReadyToStart(CompetitionConfig config, int year) { if (config.IsActive(year)) { var comp = competitionRepo.GetCompetitionForCompetitionConfig(config, year); var parents = competitionRepo.GetParentCompetitionsForCompetitionConfig(config, year).ToList(); return(config.AreAllParentsDone(year, parents) && (comp == null)); } else { return(false); } }
public void UpdateCompetitionSetups(object stateInfo = null) { var _ = Task.Run(() => { var competitions = Database.Query <CompetitionConfig>(); var allPlayers = Database.Query <Player>().ToArray(); foreach (var comp in competitions) { var memberCount = allPlayers.Count(x => x.GuildId == comp.GuildId); comp.RegistrationCount = memberCount; Database.Store(comp, CompetitionConfig.DocumentName(comp.GuildId)); } }); }
public List <MockTeam> SetupMockTeams(CompetitionConfig config) { if (config.GetType() == typeof(PlayoffCompetitionConfig)) { return(SetupMockTeams((PlayoffCompetitionConfig)config)); } else if (config.GetType() == typeof(SeasonCompetitionConfig)) { return(SetupMockTeams((SeasonCompetitionConfig)config)); } else { return(new List <MockTeam>()); } }
public virtual CompetitionConfig GetNextCompetitionConfig(CompetitionConfig current, int currentYear) { if (CompetitionConfigs == null || CompetitionConfigs.Count() == 0) { throw new Exception("Competition Configs are null"); } if (current == null) { return(CompetitionConfigs.OrderBy(c => c.Ordering).ToList().Where(c => c.IsActive(currentYear)).First()); } else { return(CompetitionConfigs.OrderBy(c => c.Ordering).ToList().Where(c => c.IsActive(currentYear) && (c.Ordering > current.Ordering)).FirstOrDefault()); } }
public async Task UndoScoreUpdatesAsync(GameResult game, CompetitionConfig competition) { foreach (var score in game.ScoreUpdates) { var player = Service.GetPlayer(Context.Guild.Id, score.Key); if (player == null) { //Skip if for whatever reason the player profile cannot be found. continue; } var currentRank = competition.MaxRank(player.Points); if (score.Value < 0) { //Points lost, so add them back player.Losses--; player.SetPoints(competition, player.Points + Math.Abs(score.Value)); } else { //Points gained so remove them player.Wins--; player.SetPoints(competition, player.Points - Math.Abs(score.Value)); } //Save the player profile after updating scores. Service.SavePlayer(player); var guildUser = Context.Guild.GetUser(player.UserId); if (guildUser == null) { //The user cannot be found in the server so skip updating their name/profile continue; } await Service.UpdateUserAsync(competition, player, guildUser); } game.GameState = State.Undecided; game.ScoreUpdates = new Dictionary <ulong, int>(); Service.SaveGame(game); }
public IEnumerable <Competition> GetParentCompetitionsForCompetitionConfig(CompetitionConfig config, int year) { var parentComps = new List <Competition>(); if (config.Parents == null) { return(new List <Competition>()); } config.Parents.ToList().ForEach(parentConfig => { var parentComp = GetCompetitionForCompetitionConfig(parentConfig, year); if (parentComp != null) { parentComps.Add(parentComp); } }); return(parentComps); }
protected Competition(CompetitionConfig competitionConfig, string name, int year, Schedule schedule, IList <TeamRanking> rankings, List <CompetitionTeam> teams, bool started, bool finished, int?startDay, int?endDay) { CompetitionConfig = competitionConfig; Name = name; Year = year; Schedule = schedule; Rankings = rankings; if (Rankings == null) { Rankings = new List <TeamRanking>(); } Teams = teams; if (Teams == null) { Teams = new List <CompetitionTeam>(); } StartDay = startDay; EndDay = endDay; Started = started; Finished = finished; }
public IActionResult Index() { var pouleTeams = Team.BuildTeamList(EredevisieConfig.EredivisieTeams, 5); var pouleRules = new List <CompetitionRule>() { new CompetitionRule(1, "Winner - Knockout fase (Seeded)", Color.Chartreuse, Color.Black), new CompetitionRule(2, "Runnerup - Knockout fase (Non-Seeded)", Color.CornflowerBlue, Color.Black), }; var fantasyCompetitionConfig = new CompetitionConfig( pouleTeams, pouleRules, 30); var pouleCompetition = new Competition(fantasyCompetitionConfig); var competitionViewModel = _mapper.Map <CompetitionViewModel>(pouleCompetition); return(View(competitionViewModel)); }
public CompetitionConfig GetOrCreateCompetition(ulong guildId) { return(Database.Load <CompetitionConfig>(CompetitionConfig.DocumentName(guildId)) ?? CreateCompetition(guildId)); }
public void SaveCompetition(CompetitionConfig comp) { Database.Store <CompetitionConfig>(comp, CompetitionConfig.DocumentName(comp.GuildId)); }
public void RunMigration(LocalManagementService local) { if (oldDatabase == null) { oldDatabase = new RavenDatabase(local); } try { var tokenModel = oldDatabase.Load <TokenModel>("tokens"); if (tokenModel != null) { currentDatabase.Store(tokenModel, "legacyELOTokens"); } using (var session = oldDatabase.DocumentStore.OpenSession()) { var query = session.Query <GuildModel>(); int guilds = 0; int games = 0; int users = 0; int lobbys = 0; using (var enumerator = session.Advanced.Stream(query)) { while (enumerator.MoveNext()) { var config = enumerator.Current.Document; try { //Do not use if new competition already exists var newComp = currentDatabase.Load <CompetitionConfig>(CompetitionConfig.DocumentName(config.ID)); if (newComp != null) { if (config.Settings.Premium.Expiry > DateTime.UtcNow) { Legacy.SaveConfig(new LegacyIntegration.LegacyPremium { GuildId = config.ID, ExpiryDate = config.Settings.Premium.Expiry }); } continue; } newComp = new CompetitionConfig(); //Do not set this due to incompatibilities with new replacements //newComp.NameFormat = config.Settings.Registration.NameFormat; newComp.UpdateNames = true; newComp.RegisterMessageTemplate = config.Settings.Registration.Message; newComp.RegisteredRankId = config.Ranks.FirstOrDefault(x => x.IsDefault)?.RoleID ?? 0; newComp.Ranks = config.Ranks.Select(x => new Rank { RoleId = x.RoleID, WinModifier = x.WinModifier, LossModifier = x.LossModifier, Points = x.Threshold }).ToList(); newComp.GuildId = config.ID; newComp.DefaultWinModifier = config.Settings.Registration.DefaultWinModifier; newComp.DefaultLossModifier = config.Settings.Registration.DefaultLossModifier; newComp.AllowReRegister = config.Settings.Registration.AllowMultiRegistration; newComp.AllowSelfRename = config.Settings.Registration.AllowMultiRegistration; newComp.AllowNegativeScore = config.Settings.GameSettings.AllowNegativeScore; newComp.BlockMultiQueueing = config.Settings.GameSettings.BlockMultiQueuing; newComp.AdminRole = config.Settings.Moderation.AdminRoles.FirstOrDefault(); newComp.ModeratorRole = config.Settings.Moderation.ModRoles.FirstOrDefault(); newComp.RegistrationCount = config.Users.Count; if (config.Settings.GameSettings.ReQueueDelay != TimeSpan.Zero) { newComp.RequeueDelay = config.Settings.GameSettings.ReQueueDelay; } //TODO: Remove user on afk if (config.Settings.Premium.Expiry > DateTime.UtcNow) { Legacy.SaveConfig(new LegacyIntegration.LegacyPremium { GuildId = config.ID, ExpiryDate = config.Settings.Premium.Expiry }); } currentDatabase.Store(newComp, CompetitionConfig.DocumentName(config.ID)); guilds++; foreach (var game in config.Results) { //Skip games for lobbys that dont exist var lobby = config.Lobbies.FirstOrDefault(x => x.ChannelID == game.LobbyID); if (lobby == null) { continue; } var newResult = new GameResult(); newResult.GameId = game.GameNumber; newResult.LobbyId = game.LobbyID; newResult.GuildId = config.ID; newResult.CreationTime = game.Time; if (game.Result == GuildModel.GameResult._Result.Canceled) { newResult.GameState = GameResult.State.Canceled; } else if (game.Result == GuildModel.GameResult._Result.Team1) { newResult.GameState = GameResult.State.Decided; newResult.WinningTeam = 1; } else if (game.Result == GuildModel.GameResult._Result.Team2) { newResult.GameState = GameResult.State.Decided; newResult.WinningTeam = 2; } else if (game.Result == GuildModel.GameResult._Result.Undecided) { newResult.GameState = GameResult.State.Undecided; } newResult.Team1.Players = game.Team1.ToHashSet(); newResult.Team2.Players = game.Team2.ToHashSet(); if (lobby.PickMode == GuildModel.Lobby._PickMode.Captains) { newResult.GamePickMode = Lobby.PickMode.Captains_HighestRanked; newResult.PickOrder = GameResult.CaptainPickOrder.PickOne; } else if (lobby.PickMode == GuildModel.Lobby._PickMode.Pick2) { newResult.GamePickMode = Lobby.PickMode.Captains_HighestRanked; newResult.PickOrder = GameResult.CaptainPickOrder.PickTwo; } else if (lobby.PickMode == GuildModel.Lobby._PickMode.CompleteRandom) { newResult.GamePickMode = Lobby.PickMode.Random; } else if (lobby.PickMode == GuildModel.Lobby._PickMode.SortByScore) { newResult.GamePickMode = Lobby.PickMode.TryBalance; } newResult.LegacyGame = true; currentDatabase.Store(newResult, GameResult.DocumentName(newResult.GameId, newResult.LobbyId, newResult.GuildId)); games++; //Untransferrable info: Captains //Unfortunately, the old ELO bot didn't store captains //Also the undogame method will not work on these } foreach (var lobby in config.Lobbies) { var newLobby = new Lobby(); newLobby.GuildId = config.ID; newLobby.ChannelId = lobby.ChannelID; newLobby.DmUsersOnGameReady = config.Settings.GameSettings.DMAnnouncements; newLobby.GameResultAnnouncementChannel = config.Settings.GameSettings.AnnouncementsChannel; newLobby.GameReadyAnnouncementChannel = config.Settings.GameSettings.AnnouncementsChannel; newLobby.PlayersPerTeam = lobby.UserLimit / 2; newLobby.Description = lobby.Description; var results = config.Results.Where(x => x.LobbyID == lobby.ChannelID).ToArray(); if (results.Length == 0) { newLobby.CurrentGameCount = 0; } else { newLobby.CurrentGameCount = results.Max(x => x.GameNumber) + 1; } if (lobby.Maps.Any()) { newLobby.MapSelector = new MapSelector(); newLobby.MapSelector.Maps = lobby.Maps.ToHashSet(); } //TODO: Lobby requeue delay if (lobby.PickMode == GuildModel.Lobby._PickMode.Captains) { newLobby.TeamPickMode = Lobby.PickMode.Captains_HighestRanked; newLobby.CaptainPickOrder = GameResult.CaptainPickOrder.PickOne; } else if (lobby.PickMode == GuildModel.Lobby._PickMode.CompleteRandom) { newLobby.TeamPickMode = Lobby.PickMode.Random; } else if (lobby.PickMode == GuildModel.Lobby._PickMode.Pick2) { newLobby.CaptainPickOrder = GameResult.CaptainPickOrder.PickTwo; newLobby.TeamPickMode = Lobby.PickMode.Captains_HighestRanked; } else if (lobby.PickMode == GuildModel.Lobby._PickMode.SortByScore) { newLobby.TeamPickMode = Lobby.PickMode.TryBalance; } currentDatabase.Store(newLobby, Lobby.DocumentName(config.ID, lobby.ChannelID)); lobbys++; } foreach (var user in config.Users) { var newUser = new Player(user.UserID, config.ID, user.Username); newUser.Points = user.Stats.Points; newUser.Wins = user.Stats.Wins; newUser.Losses = user.Stats.Losses; newUser.Draws = user.Stats.Draws; //TODO: Kills/Deaths/Assists if (user.Banned != null && user.Banned.Banned) { var length = user.Banned.ExpiryTime - DateTime.UtcNow; newUser.BanHistory.Add(new Player.Ban(length, user.Banned.Moderator, user.Banned.Reason)); } currentDatabase.Store(newUser, Player.DocumentName(config.ID, user.UserID)); users++; } } catch (Exception e) { Console.WriteLine(e); } } Console.WriteLine($"Guilds: {guilds} Lobbys: {lobbys} Games: {games} Users: {users}"); } } } catch (Exception e) { Console.WriteLine(e); } }
public Competition GetCompetitionForCompetitionConfig(CompetitionConfig config, int year) { return(baseRepo.Where(c => c.CompetitionConfig.Id == config.Id && c.Year == year).FirstOrDefault()); }
public bool IsCompetitionCompleteForYear(int year, CompetitionConfig config) { return(baseRepo.Where(c => c.Finished && c.CompetitionConfig.Id == config.Id && c.Year == year).Count() > 0); }
public async Task <List <string> > UpdateUserAsync(CompetitionConfig comp, Player player, SocketGuildUser user) { var noted = new List <string>(); try { if (user.Guild.CurrentUser.GuildPermissions.ManageRoles) { var rankMatches = comp.Ranks.Where(x => x.Points <= player.Points); if (rankMatches.Any()) { //Get the highest rank that the user can receive from the bot. var maxRank = rankMatches.Max(x => x.Points); var match = rankMatches.First(x => x.Points == maxRank); //Remove other rank roles. var gRoles = user.Guild.Roles.Where(x => rankMatches.Any(r => r.RoleId == x.Id) && x.Id != match.RoleId && x.IsEveryone == false && x.IsManaged == false && x.Position < user.Guild.CurrentUser.Hierarchy).ToList(); //Check to see if the player already has the role if (!user.Roles.Any(x => x.Id == match.RoleId)) { //Try to retrieve the role in the server var role = user.Guild.GetRole(match.RoleId); if (role != null) { if (role.Position < user.Guild.CurrentUser.Hierarchy) { await user.RemoveRolesAsync(gRoles); await user.AddRoleAsync(role); /*await user.ModifyAsync(x => * { * var ids = user.Roles.Select(r => r.Id).ToList(); * ids.RemoveAll(r => gRoles.Any(g => g.Id == r)); * ids.Remove(user.Guild.EveryoneRole.Id); * ids.Add(role.Id); * * x.RoleIds = ids; * });*/ noted.Add($"{user.Mention} received the {(role.IsMentionable ? role.Mention : role.Name)} rank"); } else { noted.Add($"The {(role.IsMentionable ? role.Mention : role.Name)} rank is above ELO bot's highest role and cannot be added to the user"); } } else { comp.Ranks.Remove(match); noted.Add($"A rank could not be found in the server and was subsequently deleted from the server config [{match.RoleId} w:{match.WinModifier} l:{match.LossModifier} p:{match.Points}]"); SaveCompetition(comp); } } } //Ensure the user has the registerd role if it exists. if (comp.RegisteredRankId != 0) { if (!user.Roles.Any(x => x.Id == comp.RegisteredRankId)) { var role = user.Guild.GetRole(comp.RegisteredRankId); if (role != null) { if (role.Position < user.Guild.CurrentUser.Hierarchy) { await user.AddRoleAsync(role); } } } } } else { noted.Add("The bot requires manage roles permissions in order to modify user roles."); } if (comp.UpdateNames) { var newName = comp.GetNickname(player); var currentName = user.Nickname ?? user.Username; //TODO: Investigate null ref here? //Not sure if newname or current name could be null. if (!currentName.Equals(newName, StringComparison.InvariantCultureIgnoreCase)) { //Use heirachy check to ensure that the bot can actually set the nickname if (user.Guild.CurrentUser.GuildPermissions.ManageNicknames) { if (user.Hierarchy < user.Guild.CurrentUser.Hierarchy) { await user.ModifyAsync(x => x.Nickname = newName); } else { noted.Add("You have a higher permission level than the bot and therefore it cannot edit your nickname."); } } else { noted.Add("The bot cannot edit your nickname as it does not have the `ManageNicknames` permission"); } } } } catch (Exception e) { noted.Add($"Issue updating {user.Mention} name/roles."); } return(noted); }
public Season(CompetitionConfig competitionConfig, string name, int year, List <SeasonDivision> divisions, List <CompetitionTeam> teams, Schedule schedule, List <TeamRanking> rankings, bool started, bool finished, int?startDay, int?endDay) : base(competitionConfig, name, year, schedule, rankings, teams, started, finished, startDay, endDay) { Divisions = divisions; }