Пример #1
0
        public async Task CreateMatchFailDueToNoItemsPlaced()
        {
            var percentage         = 12.4587;
            var percentageAsString = percentage.ToString(CultureInfo.InvariantCulture);

            var salt = "randomSalt";
            var hash = "ranomdHash";

            var creatorUser = new DatabaseModel.User("steamId", "name", "imageURl", null, DateTime.Today, DateTime.Today, false, null, 10);
            var gameMode    = new DatabaseModel.GameMode
            {
                CurrentSettingId = 1,
                IsEnabled        = true,
                Type             = GameModeHelper.GetStringFromType(GameModeType.CoinFlip),
                Id = 2
            };

            A.CallTo(() => _fakedRandomService.GeneratePercentage()).Returns(percentageAsString);
            A.CallTo(() => _fakedRandomService.GenerateSalt()).Returns(salt);
            A.CallTo(() => _fakedHashService.CreateBase64Sha512Hash(percentageAsString, salt)).Returns(hash);
            A.CallTo(() => _fakedUserRepoService.FindAsync(creatorUser.SteamId)).Returns(creatorUser);

            A.CallTo(() => _fakedGameModeRepoSerivce.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip))).Returns(gameMode);

            var itemList = new List <AssetAndDescriptionId>();

            await Assert.ThrowsAsync <InvalidBetException>(async() =>
                                                           await _coinFlipService.CreateMatch(creatorUser.SteamId, true, itemList, _defaultSetting));

            A.CallTo(() => _fakedCoinFlipMatchRepoService.InsertAsync(A <DatabaseModel.CoinFlip> ._, A <ITransactionWrapper> ._)).MustNotHaveHappened();
            A.CallTo(() => _fakedUserRepoService.FindAsync(creatorUser.SteamId)).MustHaveHappened();
        }
Пример #2
0
        public async Task CreateMatchRollBackWhenPlaceBetFailsSuccess()
        {
            var percentage         = 12.4587;
            var percentageAsString = percentage.ToString(CultureInfo.InvariantCulture);

            var salt = "randomSalt";
            var hash = "ranomdHash";

            var creatorUser = new DatabaseModel.User("steamId", "name", "imageURl", null, DateTime.Today, DateTime.Today, false, null, 10);
            var gameMode    = new DatabaseModel.GameMode
            {
                CurrentSettingId = 1,
                IsEnabled        = true,
                Type             = GameModeHelper.GetStringFromType(GameModeType.CoinFlip),
                Id = 2
            };

            A.CallTo(() => _fakedUserRepoService.FindAsync(creatorUser.SteamId)).Returns(creatorUser);
            A.CallTo(() => _fakedRandomService.GeneratePercentage()).Returns(percentageAsString);
            A.CallTo(() => _fakedRandomService.GenerateSalt()).Returns(salt);
            A.CallTo(() => _fakedHashService.CreateBase64Sha512Hash(percentageAsString, salt)).Returns(hash);
            A.CallTo(() => _fakedGameModeRepoSerivce.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip))).Returns(gameMode);

            A.CallTo(() => _fakedBetService.PlaceBetOnCoinFlipMatch
                     (
                         A <DatabaseModel.CoinFlip> ._,
                         A <JackpotMatchSetting> ._,
                         A <DatabaseModel.GameMode> ._,
                         A <int> ._,
                         A <List <DatabaseModel.Item> > ._,
                         A <DatabaseModel.User> ._,
                         A <List <DatabaseModel.ItemDescription> > ._
                     )).Throws <Exception>();

            var itemList = new List <AssetAndDescriptionId>
            {
                new AssetAndDescriptionId {
                    AssetId = "assetId1", DescriptionId = 1
                }
            };

            var didFail = false;

            try
            {
                await _coinFlipService.CreateMatch(creatorUser.SteamId, true, itemList, _defaultSetting);
            }
            catch (Exception)
            {
                didFail = true;
            }

            Assert.True(didFail, "The method did not throw!");

            A.CallTo(() => _fakedCoinFlipMatchRepoService.RemoveAsync(A <DatabaseModel.CoinFlip> ._)).MustHaveHappened();
            A.CallTo(() => _fakedJackpotSettingRepoService.RemoveAsync(A <DatabaseModel.JackpotSetting> ._)).MustHaveHappened();
            A.CallTo(() => _fakedUserRepoService.FindAsync(creatorUser.SteamId)).MustHaveHappened();
        }
Пример #3
0
        private async Task SetUpGameModeAndSetting()
        {
            var currentMatch = await _repoServiceFactory.MatchRepoService.GetCurrentMatch();

            if (currentMatch != null) //there is no matches, this is the first time we are starting the server.
            {
                _currentMatchSettings =
                    (DatabaseModel.JackpotSetting) await _gameModeSettingService.Find(currentMatch.SettingId, GameModeType.JackpotCsgo);
            }
            _gameMode = await _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo));
        }
Пример #4
0
        public async Task <object> GetSettingForType(GameModeType type)
        {
            var gameMode = await _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(type));

            switch (type)
            {
            case GameModeType.JackpotCsgo:
                return(await _repoServiceFactory.JackpotSettingRepo.Find(gameMode.CurrentSettingId));

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
        static void Prefix(StandardLevelDetailView __instance, IBeatmapLevel level, BeatmapDifficulty defaultDifficulty, BeatmapCharacteristicSO defaultBeatmapCharacteristic, PlayerData playerData)
        {
            List <BeatmapCharacteristicSO> toGenerate = new List <BeatmapCharacteristicSO>();

            if (Config.Instance.ShowGenerated360)
            {
                toGenerate.Add(GameModeHelper.GetGenerated360GameMode());
            }
            if (Config.Instance.ShowGenerated90)
            {
                toGenerate.Add(GameModeHelper.GetGenerated90GameMode());
            }

            List <IDifficultyBeatmapSet> sets = new List <IDifficultyBeatmapSet>(level.beatmapLevelData.difficultyBeatmapSets);

            // Generate each custom gamemode
            foreach (BeatmapCharacteristicSO customGameMode in toGenerate)
            {
                if (level.beatmapLevelData.difficultyBeatmapSets.Any((e) => e.beatmapCharacteristic.serializedName == GameModeHelper.GENERATED_360DEGREE_MODE))
                {
                    // Already added the generated gamemode
                    continue;
                }

                IDifficultyBeatmapSet basedOnGameMode = level.beatmapLevelData.difficultyBeatmapSets.FirstOrDefault((e) => e.beatmapCharacteristic.serializedName == Config.Instance.BasedOn);
                if (basedOnGameMode == null)
                {
                    // Level does not have a standard mode to base its 360 mode on
                    continue;
                }

                CustomDifficultyBeatmapSet customSet    = new CustomDifficultyBeatmapSet(customGameMode);
                CustomDifficultyBeatmap[]  difficulties = basedOnGameMode.difficultyBeatmaps.Select((e) => new CustomDifficultyBeatmap(e.level, customSet, e.difficulty, e.difficultyRank, e.noteJumpMovementSpeed, e.noteJumpStartBeatOffset, e.beatmapData.GetCopy())).ToArray();
                customSet.SetCustomDifficultyBeatmaps(difficulties);
                sets.Add(customSet);
            }

            // Update difficultyBeatmapSets
            if (level.beatmapLevelData is BeatmapLevelData data)
            {
                if (!FieldHelper.Set(data, "_difficultyBeatmapSets", sets.ToArray()))
                {
                    Plugin.Log.Warn("Could not set new difficulty sets");
                    return;
                }
            }
            else
            {
                Plugin.Log.Info("Unsupported beatmapLevelData: " + (level.beatmapLevelData?.GetType().FullName ?? "null"));
            }
        }
Пример #6
0
        private async void Tick()
        {
            while (_isRunning)
            {
                await Task.Delay(200);

                if (_isClosed)
                {
                    continue;
                }

                _gameMode = await _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo));


                var match = await _repoServiceFactory.MatchRepoService.GetCurrentMatch();

                var betsOnMatch = await _repoServiceFactory.BetRepoService.FindAsync(match);

                var itemBetsOnMatch = await _repoServiceFactory.ItemBettedRepoService.FindAsync(betsOnMatch);

                await ProcessQueueUntillTimeSpanIsMet(TimeSpan.Zero);

                if (ShouldStartTimmer(betsOnMatch, match))
                {
                    await StartTimmer(match.RoundId);
                }

                if (!ShouldCloseMatch(match, itemBetsOnMatch, _betQueue.Items.Count))
                {
                    continue;
                }


                _isClosed = true;
                await CloseMatch(match.RoundId);
                await ProcessQueueUntillDone();

                await DraftWinner(match);

                await Task.Delay(_currentMatchSettings.DraftingTimeInMilliSec);
                await CreateNewMatchAsync(match.RoundId + 1);
            }
        }
Пример #7
0
        public CoinFlipManagerTest()
        {
            _fakedRepoServiceFactory = A.Fake <IRepoServiceFactory>();

            _fakedCoinFlipMatchRepoService = A.Fake <ICoinFlipMatchRepoService>();
            _fakedBetRepoService           = A.Fake <IBetRepoService>();
            _fakedJackpotSettingRepo       = A.Fake <IJackpotSettingRepo>();
            _fakedGameModeRepoService      = A.Fake <IGameModeRepoService>();
            _fakedUserRepoService          = A.Fake <IUserRepoService>();

            _fakedCoinFlipService = A.Fake <ICoinFlipService>();

            _fakedDraftingService = A.Fake <IJackpotDraftService>();

            _gameMode = new DatabaseModel.GameMode
            {
                CurrentSettingId = 1,
                Id        = 2,
                IsEnabled = true,
                Type      = "CoinFlip"
            };

            _coinFlipSocketSender = A.Dummy <ICoinFlipHubConnections>();

            A.CallTo(() => _fakedRepoServiceFactory.UserRepoService).Returns(_fakedUserRepoService);
            A.CallTo(() => _fakedRepoServiceFactory.CoinFlipMatchRepoService).Returns(_fakedCoinFlipMatchRepoService);
            A.CallTo(() => _fakedRepoServiceFactory.BetRepoService).Returns(_fakedBetRepoService);
            A.CallTo(() => _fakedRepoServiceFactory.JackpotSettingRepo).Returns(_fakedJackpotSettingRepo);
            A.CallTo(() => _fakedRepoServiceFactory.GameModeRepoService).Returns(_fakedGameModeRepoService);

            A.CallTo(() => _fakedGameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip))).Returns(_gameMode);

            _dummyBetOrWithdrawQueueManager = A.Dummy <IBetOrWithdrawQueueManager>();
            _dummyBetHubConnection          = A.Dummy <IBetHubConnections>();
            _dummyBetService              = A.Dummy <IBetService>();
            _dummyLogServiceFactory       = A.Dummy <ILogServiceFactory>();
            _dummyMongoJackpotRepoService = A.Dummy <IMongoJackpotRepoService>();
            _dummyHotStatusManager        = A.Dummy <IHotStatusManager>();
            _dummyDiscordService          = A.Dummy <IDiscordService>();
        }
Пример #8
0
        private async Task FirstTimeSetUp(IContainer container)
        {
            var databaseHelperFactory = container.Resolve <IDatabaseHelperFactory>();

            var BettingSettingConnectionString   = Configuration.GetConnectionString("Master");
            var databaseHelperForBetting         = databaseHelperFactory.GetDatabaseHelperForType(Database.Main, BettingSettingConnectionString);
            var databaseHelperForBettingSettings =
                databaseHelperFactory.GetDatabaseHelperForType(Database.Settings, BettingSettingConnectionString, "[Betting.Settings]");

            var doesDatabaseExist = await ValidateDatabaseAndTableExist(databaseHelperForBettingSettings);

            var settingRepo = container.Resolve <ISettingRepoService>();

            if (!doesDatabaseExist)
            {
                Console.WriteLine("No settings table was found, Creating one!");
                await settingRepo.SetSettingsAsync(GetObjectFromConsole <DatabaseModel.Settings>());
            }

            if (!await ValidateDatabaseAndTableExist(databaseHelperForBetting))
            {
                //TODO CREATE ALL GAMEMODES HERE!
                Console.WriteLine("No JackpotSetting table was found, Creating one!");
                var jackpotSetting        = GetObjectFromConsole <DatabaseModel.JackpotSetting>();
                var jackpotSettingService = container.Resolve <IJackpotSettingRepo>();

                var jackpotId = (await jackpotSettingService.InsertAsync(jackpotSetting)).Id;

                var gameModeRepoService = container.Resolve <IGameModeRepoService>();
                await gameModeRepoService.Insert(new DatabaseModel.GameMode(GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo), jackpotId));

                await gameModeRepoService.Insert(new DatabaseModel.GameMode(GameModeHelper.GetStringFromType(GameModeType.CoinFlip), 0)); //TODO FIX THIS 0 id.

                await container.Resolve <IJackpotMatchManager>().InitGameModeWhenFreshDatabase();

                var pricingService = container.Resolve <IPricingServiceFactory>().GetPricingService(PricingServices.CsgoFast);
                await pricingService.UpdatePricingForAll();
            }
        }
Пример #9
0
        private async Task InsertBetWithTransaction
        (
            DatabaseModel.User user,
            int matchId,
            List <DatabaseModel.Item> items,
            DatabaseModel.GameMode gameMode,
            List <DatabaseModel.ItemDescription> itemDescriptions
        )
        {
            List <DatabaseModel.ItemBetted> itemBets;

            DatabaseModel.Bet insertedBet;
            List <Item>       itemModels;

            using (var transaction = _transactionFactory.BeginTransaction())
            {
                try
                {
                    var bet = new DatabaseModel.Bet(user.Id, matchId, gameMode.Id, DateTime.Now);
                    insertedBet = await _betRepoService.InsertAsync(bet, transaction);

                    itemBets = CreateItemBets(insertedBet.Id, itemDescriptions, items, out itemModels);

                    await _itemBettedRepoService.InsertAsync(itemBets, transaction);

                    transaction.Commit();
                }
                catch (SqlException e)
                {
                    throw new InvalidBetException("Can't inset bet due to sql error", e);
                }
            }

            if (gameMode.Type == GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo))
            {
                await SendWebsocketMatchEvent(user, matchId, itemModels, insertedBet);
            }
        }
Пример #10
0
        public async Task <DatabaseModel.Match> CreateNewMatchAsync(int roundId)
        {
            var settingRes = await _gameModeSettingService.GetSettingForType(GameModeType.JackpotCsgo);

            _currentMatchSettings = (DatabaseModel.JackpotSetting)settingRes ?? throw new NullReferenceException("The match setting is NULL!");

            _gameMode = await _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo));

            var res = await base.CreateNewMatchAsync(roundId, _gameMode);

            var jackpotMatch = new JackpotMatch(
                roundId.ToString(),
                res.Hash,
                res.Salt,
                res.Percentage,
                MatchStatusHelper.GetMatchStatusFromInt(res.Status),
                new List <Bet>(),
                res.TimerStarted,
                new JackpotMatchSetting(
                    _currentMatchSettings.Rake,
                    TimeSpan.FromMilliseconds(_currentMatchSettings.TimmerInMilliSec),
                    _currentMatchSettings.ItemsLimit,
                    _currentMatchSettings.MaxItemAUserCanBet,
                    _currentMatchSettings.MinItemAUserCanBet,
                    _currentMatchSettings.MaxValueAUserCanBet,
                    _currentMatchSettings.MinValueAUserCanBet,
                    _currentMatchSettings.AllowCsgo,
                    _currentMatchSettings.AllowPubg,
                    TimeSpan.FromMilliseconds(_currentMatchSettings.DraftingTimeInMilliSec),
                    _currentMatchSettings.DraftingGraph
                    )
                );

            await _matchHubConnections.NewMatchCreated(jackpotMatch);

            _isClosed = false;
            return(res);
        }
Пример #11
0
        public async Task CreateMatchSuccess()
        {
            var percentage         = 12.4587;
            var percentageAsString = percentage.ToString(CultureInfo.InvariantCulture);

            var salt = "randomSalt";
            var hash = "ranomdHash";

            var creatorUser = new DatabaseModel.User("steamId", "name", "imageURl", null, DateTime.Today, DateTime.Today, false, null, 10);
            var gameMode    = new DatabaseModel.GameMode
            {
                CurrentSettingId = 1,
                IsEnabled        = true,
                Type             = GameModeHelper.GetStringFromType(GameModeType.CoinFlip),
                Id = 2
            };

            A.CallTo(() => _fakedMongoDbPreHashRepoService.Find(hash, creatorUser.SteamId)).Returns(new MongoDbModels.PreHash
            {
                Created     = DateTime.Today,
                Hash        = hash,
                Percentage  = percentageAsString,
                Salt        = salt,
                UserSteamId = creatorUser.SteamId
            });

            A.CallTo(() => _fakedRandomService.GenerateNewGuidAsString()).Returns("GUID");
            A.CallTo(() => _fakedJackpotSettingRepoService.InsertAsync(A <DatabaseModel.JackpotSetting> ._, A <ITransactionWrapper> ._))
            .Returns(new DatabaseModel.JackpotSetting {
                Id = 1
            });


            A.CallTo(() => _fakedUserRepoService.FindAsync(creatorUser.SteamId)).Returns(creatorUser);
            A.CallTo(() => _fakedGameModeRepoSerivce.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip))).Returns(gameMode);

            var itemList = new List <AssetAndDescriptionId>
            {
                new AssetAndDescriptionId {
                    AssetId = "assetId1", DescriptionId = 1
                }
            };


            await _coinFlipService.CreateMatch(creatorUser.SteamId, true, itemList, _defaultSetting);

            A.CallTo(() => _fakedCoinFlipMatchRepoService.InsertAsync(A <DatabaseModel.CoinFlip> .That.Matches
                                                                          (m =>
                                                                          m.Created > DateTime.Today &&
                                                                          m.CreatorUserId == 10 &&
                                                                          m.CreatorIsHead == true &&
                                                                          m.Hash == hash &&
                                                                          m.Salt == salt &&
                                                                          m.Percentage == percentageAsString &&
                                                                          m.RoundId == "GUID" &&
                                                                          m.Status == (int)MatchStatus.Open &&
                                                                          m.TimerStarted == null &&
                                                                          m.WinnerId == null &&
                                                                          m.GameModeId == 2 &&
                                                                          m.SettingId == 1
                                                                          ),
                                                                      A <ITransactionWrapper> ._
                                                                      )).MustHaveHappened();

            A.CallTo(() => _fakedMongoDbPreHashRepoService.Find(hash, creatorUser.SteamId)).MustHaveHappened();
            A.CallTo(() => _fakedUserRepoService.FindAsync(creatorUser.SteamId)).MustHaveHappened();
            A.CallTo(() => _fakedTransactionWrapper.Commit()).MustHaveHappened();
            A.CallTo(() => _fakedBetService.PlaceBetOnCoinFlipMatch
                     (
                         A <DatabaseModel.CoinFlip> ._,
                         A <JackpotMatchSetting> ._,
                         A <DatabaseModel.GameMode> ._,
                         A <int> ._,
                         A <List <DatabaseModel.Item> > ._,
                         A <DatabaseModel.User> ._,
                         A <List <DatabaseModel.ItemDescription> > ._
                     )).MustHaveHappened();
            A.CallTo(() => _fakedMongoDbJackpotRepoService.InsertAsync(A <MongoDbModels.JackpotMatch> ._)).MustHaveHappened();
        }
Пример #12
0
        private async Task PlaceBetOnMatch
        (
            int matchId,
            JackpotMatchSetting setting,
            DatabaseModel.GameMode gameMode,
            int assetAndDescriptionIdsCount,
            List <DatabaseModel.Item> items,
            DatabaseModel.User user,
            List <DatabaseModel.ItemDescription> uniqueItemDescriptions
        )
        {
            if (!gameMode.IsEnabled)
            {
                throw new GameModeIsNotEnabledException($"The current gamemode {gameMode.Type} is not enabled");
            }

            if ((setting.AllowCsgo && setting.AllowPubg) == false)
            {
                var oneOrMoreItemsIsPubg = uniqueItemDescriptions.Any(AppIdToGameConverterHelper.IsPubgItem);
                var oneOrMoreItemsIsCsgo = uniqueItemDescriptions.Any(AppIdToGameConverterHelper.IsCsgoItem);

                if (setting.AllowCsgo && oneOrMoreItemsIsPubg)
                {
                    throw new NotAllowedAppIdOnMatchException("You tried to bet a PUBG item on a match that only accepts CSGO");
                }

                if (setting.AllowPubg && oneOrMoreItemsIsCsgo)
                {
                    throw new NotAllowedAppIdOnMatchException("You tried to bet a CSGO item on a match that only accepts PUBG");
                }
            }

            if (uniqueItemDescriptions.Any(description => !description.Valid))
            {
                throw new InvalidItemException("One or more items is not allowed to be used for betting at the moment, refresh the page and try again");
            }

            if (user == null)
            {
                throw new UserDoesNotExistException("Can't find a user");
            }

            if (items.Any(item => item.OwnerId != user.Id))
            {
                throw new UserDoesNotOwnThisItemsException("The user does not own this item!");
            }

            if (items.Count == 0)
            {
                throw new InvalidAssetAndDecriptionIdException("No items with that assetId or descriptionId was found");
            }

            if (items.Count != assetAndDescriptionIdsCount)
            {
                throw new NotSameCountAsExpectedException("assetAndDescriptionIds count != avalibleItems");
            }

            if (items.Count > setting.MaxItemAUserCanBet)
            {
                throw new ToManyItemsOnBetException($"You can max bet {setting.MaxItemAUserCanBet} items, you tried to bet {items.Count}");
            }

            if (items.Count < setting.MinItemAUserCanBet)
            {
                throw new ToFewItemsOnBetException($"You can min bet {setting.MinItemAUserCanBet} items, you tried to bet {items.Count}");
            }

            var sumOfBet = await _itemService.GetSumOfItems(items);

            if (sumOfBet > setting.MaxValueAUserCanBet)
            {
                throw new ToMuchValueOnBetException($"You can max bet {setting.MaxValueAUserCanBet} value, you tried to bet {sumOfBet}");
            }

            if (sumOfBet < setting.MinValueAUserCanBet)
            {
                throw new ToLittleValueOnBetException($"You can min bet {setting.MinValueAUserCanBet} value, you tried to bet {sumOfBet}");
            }


            var avalibleItems = await _itemService.GetAvalibleItemsForUser(user);

            if (avalibleItems.Count == 0)
            {
                throw new NoAvalibleItemsForBettingException("No avalible item for betting");
            }

            if (IsSameItemsInAvalibleItemsAsInItem(items, avalibleItems))
            {
                throw new ItemNotAvalibleException("This item can not be betted now! Is this items already betted on an open match?)");
            }

            await InsertBetWithTransaction(user, matchId, items, gameMode, uniqueItemDescriptions);

            //we have now successfully placed a bet

            if (gameMode.Type == GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo))
            {
                _discordService.JackpotBetAsync(matchId, user.SteamId, sumOfBet);
            }
        }
Пример #13
0
        private async void Tick()
        {
            while (_running)
            {
                await Task.Delay(200);

                _currentGamemode = await _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip));

                _hotStatusManager.RemoveExperiedHotStatuses();

                var matches = await _repoServiceFactory.CoinFlipMatchRepoService.FindAllNotClosedMatches();

                foreach (var coinFlip in matches)
                {
                    var currentMatchSetting = await _repoServiceFactory.JackpotSettingRepo.Find(coinFlip.SettingId);

                    var bets = await _repoServiceFactory.BetRepoService.FindAsync(coinFlip.Id, _currentGamemode.Id);

                    if (bets.Count > 2)
                    {
                        var e = new Exception("BETS SHOULD NEVER BE MORE THEN 2!");
                        e.Data.Add("Match", coinFlip);
                        throw e;
                    }

                    if (bets.Count == 1)
                    {
                        continue;                  // we are still wating for someone to join.
                    }
                    if (bets.Count == 0)
                    {
                        continue;                  // The create match and insert bet is done on two diffrent transactions sadly...
                    }
                    if (coinFlip.Status == (int)MatchStatus.Open)
                    {
                        var timer = DateTime.Now;
                        coinFlip.Status       = (int)MatchStatus.TimerCountdown;
                        coinFlip.TimerStarted = timer;
                        await _repoServiceFactory.CoinFlipMatchRepoService.UpdateAsync(coinFlip);

                        await _jackpotRepoService.UpdateStatusForMatch(coinFlip, MatchStatus.TimerCountdown);

                        await _jackpotRepoService.UpdateTimmerStartedForMatch(coinFlip, timer);

                        await SendWebSocketEventPlayerJoinedAndInsertCoinFlipBetToMongoDb(coinFlip, currentMatchSetting, bets);

                        continue;
                    }

                    if (!coinFlip.TimerStarted.HasValue)
                    {
                        var e = new Exception("Timmer should always have a value here!");
                        e.Data.Add("match", coinFlip);
                        throw e;
                    }


                    if (coinFlip.Status == (int)MatchStatus.TimerCountdown)
                    {
                        if (!IsTimerDone(currentMatchSetting, coinFlip))
                        {
                            continue;
                        }

                        //Timer is done, start drafting!
                        await DraftWinner(coinFlip, currentMatchSetting, bets);

                        continue;
                    }

                    if (coinFlip.Status == (int)MatchStatus.Drafting)
                    {
                        if (!IsDraftingDone(currentMatchSetting, coinFlip))
                        {
                            continue;
                        }
                        coinFlip.Status = (int)MatchStatus.Closed;
                        await _repoServiceFactory.CoinFlipMatchRepoService.UpdateAsync(coinFlip);

                        await _jackpotRepoService.UpdateStatusForMatch(coinFlip, MatchStatus.Closed);

                        await _coinFlipHubConnections.MatchClosed(coinFlip);

                        continue;
                    }
                }
            }

            _didStopGracefully = true;
        }
Пример #14
0
 private async Task Setup()
 {
     _currentGamemode = await _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip));
 }
Пример #15
0
        public async Task <List <Item> > GetAvalibleItemsForUser(DatabaseModel.User user)
        {
            var jackpotGameModeTask  = _gameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo));
            var coinFlipGameModeTask = _gameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip));

            var currentMatchTask             = _matchRepoService.GetCurrentMatch();
            var notClosedCoinFlipmatchesTask = _coinFlipMatchRepoService.FindAllNotClosedMatches();

            await Task.WhenAll(jackpotGameModeTask, coinFlipGameModeTask, currentMatchTask, notClosedCoinFlipmatchesTask);

            var coinFlipGameMode         = coinFlipGameModeTask.Result;
            var currentMatch             = currentMatchTask.Result;
            var jackpotGameMode          = jackpotGameModeTask.Result;
            var notClosedCoinFlipmatches = notClosedCoinFlipmatchesTask.Result;

            var coinflipLookUpGameModeBet = new LookUpGameModeBet
            {
                GameMode = coinFlipGameMode,
                User     = user,
                MatchIds = notClosedCoinFlipmatches.Select(coin => coin.Id).ToList()
            };

            var jackpotLookUpGameModeBet = new LookUpGameModeBet
            {
                GameMode = jackpotGameMode,
                User     = user,
                MatchIds = new List <int> {
                    currentMatch.Id
                }
            };

            var userBets = await _betRepoService.FindAsync(new List <LookUpGameModeBet>
            {
                coinflipLookUpGameModeBet,
                jackpotLookUpGameModeBet
            });

            var offers = await _offerTransactionRepoService.FindActiveAsync(user);


            var itemThatUserOwns = await GetItemsThatUsersOwns(user);

            if (userBets.Count == 0 && offers.Count == 0)
            {
                return(itemThatUserOwns);
            }


            if (userBets.Count > 0 && offers.Count == 0)
            {
                return(await GetNoneBetedItems(userBets, itemThatUserOwns));
            }


            if (userBets.Count == 0 && offers.Count > 0)
            {
                return(await GetItemsThatIsNotInAOffer(offers, itemThatUserOwns));
            }


            var itemNotInOffer = await GetItemsThatIsNotInAOffer(offers, itemThatUserOwns);

            var itemNotInBetAndNotInOffer = await GetNoneBetedItems(userBets, itemNotInOffer);

            return(itemNotInBetAndNotInOffer);
        }
Пример #16
0
        public async Task InitTest()
        {
            ConnectionString = new ConnectionStringsForTest().GetConnectionString(DatabaseName);
            Database         = new DatabaseConnection(ConnectionString);

            var fakedFactory = A.Fake <IDatabaseConnectionFactory>();

            A.CallTo(() => fakedFactory.GetDatabaseConnection(Factories.Database.Main)).Returns(Database);

            var userRepo                 = new UserRepoService(fakedFactory, new UserQueries());
            var matchRepoService         = new MatchRepoService(fakedFactory, new MatchQueries());
            var coinFlipMatchRepoService = new CoinFlipMatchRepoService(fakedFactory);

            var gameModeRepoService = new GameModeRepoService(fakedFactory);

            var gameMode  = new DatabaseModel.GameMode(GameModeHelper.GetStringFromType(GameModeType.JackpotCsgo), 1);
            var gameMode1 = new DatabaseModel.GameMode(GameModeHelper.GetStringFromType(GameModeType.CoinFlip), 1);

            GameMode = await gameModeRepoService.Insert(gameMode);

            GameMode1 = await gameModeRepoService.Insert(gameMode1);

            User1 = await userRepo.InsertAsync(new DatabaseModel.User(
                                                   "987654321",
                                                   "Kalle",
                                                   " ba/bab154f01140ec39b2986d97838f0127534ec82d_full.jpg ",
                                                   "?partner=117688384&token=mn347bmb ",
                                                   DateTime.Now,
                                                   DateTime.Now,
                                                   false
                                                   ));

            User2 = await userRepo.InsertAsync(new DatabaseModel.User(
                                                   "987154321",
                                                   "Kalle",
                                                   " ba/bab154f01140ec39b2986d97838f0127534ec82d_full.jpg ",
                                                   "?partner=117688384&token=mn347bmb ",
                                                   DateTime.Now,
                                                   DateTime.Now,
                                                   false
                                                   ));

            User3 = await userRepo.InsertAsync(new DatabaseModel.User(
                                                   "983654321",
                                                   "Kalle",
                                                   " ba/bab154f01140ec39b2986d97838f0127534ec82d_full.jpg ",
                                                   "?partner=117688384&token=mn347bmb ",
                                                   DateTime.Now,
                                                   DateTime.Now,
                                                   false
                                                   ));

            User4 = await userRepo.InsertAsync(new DatabaseModel.User(
                                                   "983656584",
                                                   "Kalle",
                                                   " ba/bab154f01140ec39b2986d97838f0127534ec82d_full.jpg ",
                                                   "?partner=117688384&token=mn347bmb ",
                                                   DateTime.Now,
                                                   DateTime.Now,
                                                   false
                                                   ));

            Match1 = await matchRepoService.InsertAsync(new DatabaseModel.Match(
                                                            11,
                                                            "salt",
                                                            "hash",
                                                            47.5484.ToString(CultureInfo.InvariantCulture),
                                                            1,
                                                            null,
                                                            null,
                                                            1,
                                                            GameMode.Id,
                                                            DateTime.Now
                                                            ));

            Match2 = await matchRepoService.InsertAsync(new DatabaseModel.Match(
                                                            12,
                                                            "salt",
                                                            "hash",
                                                            47.5484.ToString(CultureInfo.InvariantCulture),
                                                            1,
                                                            null,
                                                            null,
                                                            1,
                                                            GameMode.Id,
                                                            DateTime.Now
                                                            ));

            Match3 = await matchRepoService.InsertAsync(new DatabaseModel.Match(
                                                            13,
                                                            "salt",
                                                            "hash",
                                                            47.5484.ToString(CultureInfo.InvariantCulture),
                                                            1,
                                                            null,
                                                            null,
                                                            1,
                                                            GameMode.Id,
                                                            DateTime.Now
                                                            ));

            using (var transaction = new TransactionWrapperWrapper(Database))
            {
                CoinFlip1 = await coinFlipMatchRepoService.InsertAsync(new DatabaseModel.CoinFlip
                {
                    Created       = DateTime.Today,
                    CreatorIsHead = true,
                    CreatorUserId = User1.Id,
                    GameModeId    = gameMode1.Id,
                    Hash          = "",
                    Percentage    = "",
                    Salt          = "",
                    RoundId       = "xF!",
                    SettingId     = 0,
                    Status        = 1,
                    TimerStarted  = null,
                    WinnerId      = null
                }, transaction);

                CoinFlip2 = await coinFlipMatchRepoService.InsertAsync(new DatabaseModel.CoinFlip
                {
                    Created       = DateTime.Today,
                    CreatorIsHead = true,
                    CreatorUserId = User1.Id,
                    GameModeId    = gameMode1.Id,
                    Hash          = "",
                    Percentage    = "",
                    Salt          = "",
                    RoundId       = "xD1",
                    SettingId     = 0,
                    Status        = 1,
                    TimerStarted  = null,
                    WinnerId      = null
                }, transaction);

                CoinFlip3 = await coinFlipMatchRepoService.InsertAsync(new DatabaseModel.CoinFlip
                {
                    Created       = DateTime.Today,
                    CreatorIsHead = true,
                    CreatorUserId = User1.Id,
                    GameModeId    = gameMode1.Id,
                    Hash          = "",
                    Percentage    = "",
                    Salt          = "",
                    RoundId       = "xD",
                    SettingId     = 0,
                    Status        = 1,
                    TimerStarted  = null,
                    WinnerId      = null
                }, transaction);

                transaction.Commit();
            }
        }
Пример #17
0
        public async Task <CoinFlipMatch> CreateMatch
        (
            string creatorSteamId,
            bool creatorIsHead,
            List <AssetAndDescriptionId> assetAndDescriptionIds,
            CreateCoinFlipSettingModel setting
        )
        {
            var user = await _repoServiceFactory.UserRepoService.FindAsync(creatorSteamId);

            if (user == null)
            {
                throw new UserDoesNotExistException($"The user does with steamId {creatorSteamId} not exist.");
            }

            if (assetAndDescriptionIds.Count == 0)
            {
                throw new InvalidBetException("No items selected");
            }

            var items = await _repoServiceFactory.ItemRepoService.FindAsync(assetAndDescriptionIds);

            var totalValueOfItems = await _itemService.GetSumOfItems(items);

            var jackpotSetting      = CreateJackpotSetting(setting, totalValueOfItems);
            var jackpotMatchSetting = jackpotSetting.ToJackpotMatchSetting();

            var itemDescsIds = assetAndDescriptionIds.Select(item => item.DescriptionId).Distinct().ToList();

            var itemDescriptionTask = _repoServiceFactory.ItemDescriptionRepoService.FindAsync(itemDescsIds);
            var gameModeTask        = _repoServiceFactory.GameModeRepoService.Find(GameModeHelper.GetStringFromType(GameModeType.CoinFlip));
            var getPreHashTask      = _preHashRepoService.Find(setting.PreHash, creatorSteamId);

            await Task.WhenAll(gameModeTask, itemDescriptionTask, getPreHashTask);

            if (!gameModeTask.Result.IsEnabled)
            {
                throw new GameModeIsNotEnabledException("The current gamemode CoinFlip is not enabled at the moment.");
            }

            var match = CreateCoinFlipMatch(creatorIsHead, user, gameModeTask.Result, getPreHashTask.Result);


            var insertedMatch = await InsertedMatchAndBetWithTransaction
                                (
                assetAndDescriptionIds,
                match,
                jackpotSetting,
                gameModeTask.Result,
                items,
                user,
                itemDescriptionTask.Result,
                jackpotMatchSetting
                                );

            var mongoDbMatch = await InsertIntoMongoDb(insertedMatch, items, itemDescriptionTask.Result, jackpotMatchSetting, user);

            var coinFlipMatch = new CoinFlipMatch(mongoDbMatch);

            await _coinFlipHubConnections.MatchCreated(coinFlipMatch);

            _discordService.CoinFlipCreateAsync(setting.AllowCsgo, setting.AllowPubg, totalValueOfItems, match.RoundId, user.SteamId);

            return(coinFlipMatch);
        }