public HttpResponseMessage Put(string id, Sticky sticky) { using (var session = RavenDatabase.GetSession()) { var boardRepo = new BoardRepository(session); var board = boardRepo.Get(); var existingSticky = board.Stickies.Where(s => s.Id == id).FirstOrDefault(); if (existingSticky == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Sticky with that id not found.")); } else { existingSticky.Content = sticky.Content; existingSticky.X = sticky.X; existingSticky.Y = sticky.Y; existingSticky.Height = sticky.Height; existingSticky.Width = sticky.Width; boardRepo.Save(board); return(Request.CreateResponse(HttpStatusCode.OK)); } } }
private Board GetBoardFromDatabase() { using (var session = RavenDatabase.GetSession()) { var repo = new BoardRepository(session); return(repo.Get()); } }
public HttpResponseMessage Post(Sticky sticky) { using (var session = RavenDatabase.GetSession()) { var boardRepo = new BoardRepository(session); var board = boardRepo.Get(); board.AddSticky(sticky); boardRepo.Save(board); } return(Request.CreateResponse <string>(HttpStatusCode.OK, sticky.Id)); }
public HttpResponseMessage Get(string id) { using (var session = RavenDatabase.GetSession()) { var boardRepo = new BoardRepository(session); var board = boardRepo.Get(); var sticky = board.Stickies.Where(s => s.Id == id).FirstOrDefault(); if (sticky == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Sticky with that id not found.")); } else { return(Request.CreateResponse <Sticky>(HttpStatusCode.OK, sticky)); } } }
public async Task RunAsync(string[] args = null) { string dbPathOverride = null; if (args != null) { Parser.Default.ParseArguments <Options>(args) .WithParsed <Options>(o => { if (o.Path != null) { LocalManagementService.ConfigPath = o.Path; } if (o.DatabaseConfigPath != null) { dbPathOverride = o.DatabaseConfigPath; } }); } var localManagement = new LocalManagementService(); IDatabase database = new RavenDatabase(localManagement); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => typeof(IServiceable).IsAssignableFrom(p) && !p.IsInterface); IServiceCollection collection = new ServiceCollection(); foreach (var type in types) { collection = collection.AddSingleton(type); } //Configure the service provider with all relevant and required services to be injected into other classes. Provider = collection .AddSingleton(database) .AddSingleton(x => new DiscordShardedClient(new DiscordSocketConfig { AlwaysDownloadUsers = false, MessageCacheSize = 50, LogLevel = LogSeverity.Info, ExclusiveBulkDelete = true, //You may want to edit the shard count as the bot grows more and more popular. //Discord will block single shards that try to connect to more than 2500 servers //May be advisable to fetch from a config file OR default to 1 TotalShards = 1 })) .AddSingleton(x => new LogHandler(x.GetRequiredService <DiscordShardedClient>(), x.GetRequiredService <IDatabase>())) .AddSingleton(localManagement) .AddSingleton(x => { //Initialize the bot config by asking for token and name var config = x.GetRequiredService <IDatabase>().Load <BotConfig>("BotConfig"); if (config == null) { Console.WriteLine("Please enter your bot token (found at https://discordapp.com/developers/applications/ )"); var token = Console.ReadLine(); Console.WriteLine("Input a bot name (this will be used for certain database tasks)"); var name = Console.ReadLine(); Console.WriteLine("Input a bot prefix (this will be used to run commands, ie. prefix = f. command will be f.command)"); var prefix = Console.ReadLine(); config = new BotConfig(token, prefix, name); x.GetRequiredService <IDatabase>().Store(config, "BotConfig"); } return(config); }) .AddSingleton <DeveloperSettings>() .AddSingleton <GuildService>() //.AddSingleton(x => new ModuleManagementService(x.GetRequiredService<IDatabase>(), x.GetRequiredService<PrefixService>(), localConfig.Developer)) .AddSingleton(x => new HelpService(x.GetRequiredService <CommandService>(), x.GetRequiredService <BotConfig>(), x.GetRequiredService <GuildService>(), x.GetRequiredService <DeveloperSettings>(), x)) .AddSingleton(new CommandService(new CommandServiceConfig { ThrowOnError = false, CaseSensitiveCommands = false, IgnoreExtraArgs = false, DefaultRunMode = RunMode.Async, LogLevel = LogSeverity.Info })) //.AddSingleton(x => new PrefixService(x.GetRequiredService<IDatabase>(), localConfig.Developer ? localConfig.DeveloperPrefix : x.GetRequiredService<BotConfig>().Prefix)) .AddSingleton <EventHandler>() .AddSingleton(x => new LicenseService(x.GetRequiredService <IDatabase>())) .AddSingleton <Random>() .AddSingleton <HttpClient>() .BuildServiceProvider(); try { await Provider.GetRequiredService <EventHandler>().InitializeAsync(); } catch (Exception e) { Console.WriteLine(e); throw; } await Task.Delay(-1); }
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); } }