Ejemplo n.º 1
0
        public async Task <IActionResult> EntryPlayer([FromBody] EntryPlayer.Request req)
        {
            if (req.pingResults != null)
            {
                var results = new List <LogModels.PingResults.Result>();
                foreach (var pingResult in req.pingResults)
                {
                    results.Add(new LogModels.PingResults.Result
                    {
                        regionCode = pingResult.regionCode,
                        time       = pingResult.time,
                    });
                }

                Logger.Logging(
                    new LogObj().AddChild(new LogModels.PingResults
                {
                    PlayerId = SelfHost.playerInfo.playerId,
                    Results  = results,
                })
                    );
            }


            if (!VersionChecker.Get(VersionChecker.CheckTarget.EnabledMatchmake).Check())
            {
                return(BuildErrorResponse(Error.LowCode.DisabledMatchmake));
            }

            var requester = new evomatching.ProtocolModels.Matching.EntryPlayer();

            requester.request.playerId  = SelfHost.playerInfo.playerId;
            requester.request.matchType = req.matchType.Value;
            var response = await requester.PostAsyncXXX(MatchingServerInfo.AreaUri(SelfHost.matchingArea));

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(BuildErrorResponse(Error.LowCode.ServerInternalError));
            }

            switch (response.Payload.resultCode)
            {
            case evomatching.ProtocolModels.Matching.EntryPlayer.Response.ResultCode.Ok:
                return(Ok(new EntryPlayer.Response()));

            case evomatching.ProtocolModels.Matching.EntryPlayer.Response.ResultCode.OldPackageVersion:
                return(BuildErrorResponse(Error.LowCode.NgPackageVersion));

            case evomatching.ProtocolModels.Matching.EntryPlayer.Response.ResultCode.SendedPgInvitation:
                return(BuildErrorResponse(Error.LowCode.SentPgInvitation));

            case evomatching.ProtocolModels.Matching.EntryPlayer.Response.ResultCode.RecievedPgInvitation:
                return(BuildErrorResponse(Error.LowCode.RecievedPgInvitation));

            default:
                return(BuildErrorResponse(Error.LowCode.CouldNotMatchingEnty));
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> SearchAllReplay([FromBody] SearchAllReplay.Request req)
        {
            // get data from DB
            int selectNum = req.getNum.Value;
            var query     = Common3DB.ReplayInfoAllMatch.OrderByDescending(
                i => i.date
                ).Take(selectNum);
            var replaySrc = await query.ToListAsync();

            // check version
            var checker = VersionChecker.Get(VersionChecker.CheckTarget.Replay);

            for (int i = replaySrc.Count - 1; i >= 0; i--)
            {
                checker.PackageVersion    = replaySrc[i].packageVersion;
                checker.MasterDataVersion = replaySrc[i].masterDataVersion;
                if (!checker.Check())
                {
                    replaySrc.RemoveAt(i);
                }
            }

            var infoDst = new List <SearchAllReplay.UserReplayInfo>();

            // response data
            replaySrc.ForEach(
                i => infoDst.Add(new SearchAllReplay.UserReplayInfo()
            {
                date      = i.date,
                matchType = i.matchType,
                gameMode  = i.gameMode,
                totalTime = i.totalTime,
                mvpUnit   = i.mvpUnitId,
                matchId   = i.matchId,
                result    = i.result,
                mapId     = i.mapId,
                mvpPlayer = i.mvpUserName,
            })
                );

            var res = new SearchAllReplay.Response();

            res.ReplayInfos = infoDst;

            return(Ok(res));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> SearchUserReplay([FromBody] SearchUserReplay.Request req)
        {
            // get UserPlay data
            int selectNum  = req.getNum.Value;
            var personalDb = PDBSM.PersonalDBContext(SelfHost.playerInfo.playerId);
            var userSelect = personalDb.ReplayUserHistory.Where(i =>
                                                                i.playerId == SelfHost.playerInfo.playerId
                                                                );

            if (req.matchType >= 0)
            {
                userSelect = userSelect.Where(i => i.matchType == req.matchType);
            }
            userSelect = userSelect.OrderByDescending(
                i => i.date
                );
            userSelect = userSelect.Take(selectNum);
            var userSrc = await userSelect.ToListAsync();


            // check version
            var checker = VersionChecker.Get(VersionChecker.CheckTarget.Replay);

            for (int i = userSrc.Count - 1; i >= 0; i--)
            {
                checker.PackageVersion    = userSrc[i].packageVersion;
                checker.MasterDataVersion = userSrc[i].masterDataVersion;
                if (!checker.Check())
                {
                    userSrc.RemoveAt(i);
                }
            }
            // Make match-id array
            string[] ids = new string[userSrc.Count];
            for (int i = 0; i < userSrc.Count; i++)
            {
                ids[i] = userSrc[i].matchId;
            }

            // main data
            var query = Common3DB.ReplayInfoAllMatch.Where(i =>
                                                           ids.Contains(i.matchId)
                                                           );
            var replaySrc = await query.ToListAsync();

            // response data
            var infoDst = new List <SearchUserReplay.UserReplayInfo>();

            foreach (var oneData in userSrc)
            {
                var temp = new SearchUserReplay.UserReplayInfo();
                temp.date      = oneData.date;
                temp.matchType = oneData.matchType;
                temp.matchId   = oneData.matchId;
                temp.result    = oneData.resultType.ToString(); // Win or Defeat string

                var rData = replaySrc.FirstOrDefault(i => i.matchId == oneData.matchId);
                if (rData != null)
                {
                    temp.gameMode  = rData.gameMode;
                    temp.totalTime = rData.totalTime;
                    temp.mvpUnit   = rData.mvpUnitId;
                    temp.matchId   = rData.matchId;
                    temp.mapId     = rData.mapId;
                    temp.mvpPlayer = rData.mvpUserName;
                }

                infoDst.Add(temp);
            }

            var res = new SearchUserReplay.Response();

            res.ReplayInfos = infoDst;

            return(Ok(res));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> SearchFeaturedReplay([FromBody] SearchFeaturedReplay.Request req)
        {
            int selectNum = req.getNum.Value;

            // RankMatch data at FeaturedFlag ON
            var rankSelect = Common3DB.ReplayInfoRankMatch.Where(i =>
                                                                 i.isFeatured == true
                                                                 ).OrderByDescending(
                i => i.date
                ).Take(selectNum);
            var rankSrc = await rankSelect.ToListAsync();


            // check version
            var checker = VersionChecker.Get(VersionChecker.CheckTarget.Replay);

            for (int i = rankSrc.Count - 1; i >= 0; i--)
            {
                checker.PackageVersion    = rankSrc[i].packageVersion;
                checker.MasterDataVersion = rankSrc[i].masterDataVersion;
                if (!checker.Check())
                {
                    rankSrc.RemoveAt(i);
                }
            }
            // Make match-id array
            string[] ids = new string[rankSrc.Count];
            for (int i = 0; i < rankSrc.Count; i++)
            {
                ids[i] = rankSrc[i].matchId;
            }

            // main data
            var query = Common3DB.ReplayInfoAllMatch.Where(i =>
                                                           ids.Contains(i.matchId)
                                                           );
            var replaySrc = await query.ToListAsync();

            // Match Members
            var memberquery = Common3DB.MatchMember.Where(i =>
                                                          ids.Contains(i.matchId)
                                                          );
            var membersSrc = await memberquery.ToListAsync();

            // View Num
            var viewquery = Common3DB.ReplayViewNum.Where(i =>
                                                          ids.Contains(i.matchId)
                                                          );
            var viewnumSrc = await viewquery.ToListAsync();

            // response data
            var infoDst = new List <SearchFeaturedReplay.FeaturedInfo>();

            foreach (var oneData in rankSrc)
            {
                var temp = new SearchFeaturedReplay.FeaturedInfo();
                temp.date          = oneData.date;
                temp.matchId       = oneData.matchId;
                temp.ratingAverage = oneData.ratingAverage;// for Rank

                var rData = replaySrc.FirstOrDefault(i => i.matchId == oneData.matchId);
                if (rData != null)
                {
                    temp.gameMode  = rData.gameMode;
                    temp.totalTime = rData.totalTime;
                    temp.mvpUnit   = rData.mvpUnitId;
                    temp.matchId   = rData.matchId;
                    temp.result    = rData.result;
                    temp.mapId     = rData.mapId;
                    temp.mvpPlayer = rData.mvpUserName;
                }

                var memberinfo = membersSrc.FirstOrDefault(i => i.matchId == oneData.matchId);
                if (memberinfo != null)
                {
                    temp.members = memberinfo.playersInfo;
                }

                var numdata = viewnumSrc.FirstOrDefault(i => i.matchId == oneData.matchId);
                if (numdata != null)
                {
                    temp.viewNum = numdata.ViewNum;
                }

                infoDst.Add(temp);
            }

            var res = new SearchFeaturedReplay.Response();

            res.FeaturedInfos = infoDst;

            return(Ok(res));
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> SearchRankReplay([FromBody] SearchRankReplay.Request req)
        {
            int selectNum = req.getNum.Value;

            // 出撃機体フィルタ作成
            UInt64 spawn = 0;

            if (req.filter.spawnUnits.Count > 0)
            {
                foreach (int bit_idx in req.filter.spawnUnits)
                {
                    UInt64 mask = (UInt64)(1 << bit_idx);
                    spawn |= mask;
                }
            }
            // 表彰機体フィルタ作成
            UInt64 award = 0;

            if (req.filter.awardUnits.Count > 0)
            {
                foreach (int bit_idx in req.filter.awardUnits)
                {
                    UInt64 mask = (UInt64)(1 << bit_idx);
                    award |= mask;
                }
            }

            var checker = VersionChecker.Get(VersionChecker.CheckTarget.Replay);
            var rankSrc = new List <ReplayInfoRankMatch>();

            // 指定件数の2倍を仮取得
            var tempData = await Common3DB.ReplayInfoRankMatch.OrderByDescending(
                i => i.date
                ).Take(selectNum * 2).ToListAsync();

            // TODO:このリクエストは全ユーザ共通のDB検索結果となるため、tempDataはAPIサーバーにローカルキャッシュするなどして
            //       せめて同じAPIサーバーを利用するユーザ間で共有したい。

            // 仮取得したデータを全チェック
            foreach (var oneLow in tempData)
            {
                checker.PackageVersion    = oneLow.packageVersion;
                checker.MasterDataVersion = oneLow.masterDataVersion;
                if (!checker.Check())
                {
                    break;                    // 日付降順に取得しているのでバージョン不適合があればそれより昔のデータは全部不適合なので終了
                }

                if (req.filter.gameMode > 0 && oneLow.gameMode != req.filter.gameMode)
                {
                    continue;                    //GameMode が違う
                }
                if (req.filter.mapId.Length > 0 && oneLow.mapId != req.filter.mapId)
                {
                    continue;                    // Map が違う
                }
                if (req.filter.ratingBottom > 0)
                {
                    if (oneLow.ratingAverage < req.filter.ratingBottom || req.filter.ratingUpper <= oneLow.ratingAverage)
                    {
                        continue;                        //指定ランク帯と違う
                    }
                }
                if (spawn > 0 && (spawn & oneLow.spawnUnits) == 0)
                {
                    continue;                    // 出撃機体指定が1つも当てはまらない
                }
                if (award > 0 && (award & oneLow.awardUnits) == 0)
                {
                    continue;                    // 表彰機体指定が1つも当てはまらない
                }

                // 厳しい条件を乗り越え、検索結果として有効だったデータ
                rankSrc.Add(oneLow);

                // 指定件数集まれば即終了
                if (rankSrc.Count >= selectNum)
                {
                    break;
                }
            }

            //-------- 検索ここまで、これ以降は詳細データのアタッチ ---------------

            // Make match-id array
            string[] ids = new string[selectNum];
            for (int i = 0; i < rankSrc.Count; i++)
            {
                ids[i] = rankSrc[i].matchId;
            }

            // main data
            var query = Common3DB.ReplayInfoAllMatch.Where(i =>
                                                           ids.Contains(i.matchId)
                                                           );
            var replaySrc = await query.ToListAsync();

            // View Num
            var viewquery = Common3DB.ReplayViewNum.Where(i =>
                                                          ids.Contains(i.matchId)
                                                          );
            var viewnumSrc = await viewquery.ToListAsync();

            // response data
            var infoDst = new List <SearchRankReplay.UserReplayInfo>();

            foreach (var oneData in rankSrc)
            {
                var temp = new SearchRankReplay.UserReplayInfo();
                temp.date          = oneData.date;
                temp.matchType     = evolib.Battle.MatchType.Rank;
                temp.matchId       = oneData.matchId;
                temp.ratingAverage = oneData.ratingAverage;// for Rank

                var rData = replaySrc.FirstOrDefault(i => i.matchId == oneData.matchId);
                if (rData != null)
                {
                    temp.gameMode  = rData.gameMode;
                    temp.totalTime = rData.totalTime;
                    temp.mvpUnit   = rData.mvpUnitId;
                    temp.matchId   = rData.matchId;
                    temp.result    = rData.result;
                    temp.mapId     = rData.mapId;
                    temp.mvpPlayer = rData.mvpUserName;
                }

                var numdata = viewnumSrc.FirstOrDefault(i => i.matchId == oneData.matchId);
                if (numdata != null)
                {
                    temp.viewNum = numdata.ViewNum;
                }

                infoDst.Add(temp);
            }

            var res = new SearchRankReplay.Response();

            res.ReplayInfos = infoDst;

            return(Ok(res));
        }
Ejemplo n.º 6
0
        public void Start()
        {
            PgInvitationManager = new PgInvitationManager();
            PremadeGroupManager = new PremadeGroupManager();
            BattleEntryManager  = new BattleEntryManager();
            MatchManager        = new MatchManager();

            var matchMaker = new Logic.Matchmaker2();


            var sessionCheckTimer       = new IntervalTimer(5000);
            var autoMatchmakeTimer      = new IntervalTimer(30000);
            var generateSessionCntTimer = new IntervalTimer(5000);
            var LogSessionCntTimer      = new IntervalTimer(30000);


            Task.Run(async() =>
            {
                while (true)
                {
                    if (Settings.MatchingArea != MatchingArea.Unknown)
                    {
                        WatchDogSession = new WatchDogSession(Settings.MatchingArea);
                        break;
                    }

                    await Task.Delay(1000);
                }

                var enabledMatchesCnt = 0;
                var entriedPlayersCnt = 0;

                while (true)
                {
                    // -----------------------------------------
                    // Session有効確認
                    // -----------------------------------------
                    if (sessionCheckTimer.Timeup())
                    {
                        var tmp = EnqueueJob(async() =>
                        {
                            BattleEntryManager.CheckSessions(WatchDogSession.Alive);

                            MatchManager.CheckSessions(WatchDogSession.Alive);

                            PgInvitationManager.ClearExpiredInvitations();                            //Clear!! ExpiredInvitations

                            var changedPlayers = PremadeGroupManager.CheckSessions(WatchDogSession.Alive);

                            for (int i = 0; i < changedPlayers.Count; i++)
                            {
                                var player = changedPlayers[i];

                                await new evolib.Kvs.Models.ConnectionQueue(player.SessionId).EnqueueAsync(
                                    this.CreatePremadeGroupQueueData(player.PlayerId)
                                    );
                            }

                            sessionCheckTimer.Start();
                        });
                    }

                    // -----------------------------------------
                    // Auto Matchmake
                    // -----------------------------------------
                    if (autoMatchmakeTimer.Timeup())
                    {
                        var tmp = EnqueueJob(async() =>
                        {
                            var enabledMatches =
                                MatchManager.GatherMatches(m =>
                            {
                                return
                                (m.State == MatchState.Matching && m.Server.AutoMatchmakeTarget);
                            });

                            enabledMatchesCnt = enabledMatches.Count;
                            entriedPlayersCnt = BattleEntryManager.EntriedPlayersCount;


                            if (VersionChecker.Get(VersionChecker.CheckTarget.EnabledMatchmake).Check())
                            {
                                var limitPackagerVer = VersionChecker.Valued(
                                    VersionChecker.ReferenceSrc.PackageVersion,
                                    VersionChecker.LimitPackageVersion(VersionChecker.CheckTarget.Matchmake)
                                    );

                                var minMatchmakeEntriedPlayersNumber = MinMatchmakeEntriedPlayersNumber.Pop(null);
                                using (var common2Db = DbContextFactory.CreateCommon2())
                                {
                                    minMatchmakeEntriedPlayersNumber = MinMatchmakeEntriedPlayersNumber.Pop(
                                        await common2Db.GenericDatas.FindAsync(GenericData.Type.MinMatchmakeEntriedPlayersNumber)
                                        );
                                }


                                var result = matchMaker.MatchmakeForCBT1(
                                    enabledMatches.Count,
                                    BattleEntryManager.GetEntries(e =>
                                {
                                    return(limitPackagerVer <= e.MinPackageVersion);
                                },
                                                                  5000),
                                    minMatchmakeEntriedPlayersNumber
                                    );

                                // Sort by entryTime.
                                enabledMatches.Sort((a, b) => (a.Server.EntryTime < b.Server.EntryTime) ? -1 : 1);

                                for (int i = 0; i < result.Count; i++)
                                {
                                    var match = enabledMatches[i];

                                    var matchmake = result[i];

                                    var players = new Dictionary <string, long>();

                                    foreach (var e in matchmake.Elements)
                                    {
                                        if (MatchManager.AssignPlayers(
                                                match.MatchId,
                                                e.Entry.Players,
                                                e.Side))
                                        {
                                            BattleEntryManager.Cancel(e.Entry.EntryId, match.MatchId, evolib.BattleEntry.Type.Matching);

                                            foreach (var p in e.Entry.Players)
                                            {
                                                players[p.SessionId] = p.PlayerId;
                                            }
                                        }
                                    }

                                    foreach (var p in players)
                                    {
                                        await new ConnectionQueue(p.Key).EnqueueAsync(
                                            match.JoinBattleServer(p.Value)
                                            );
                                    }

                                    await new ConnectionQueue(match.Server.SessionId).EnqueueAsync(
                                        match.MatchInfo()
                                        );
                                }
                            }

                            autoMatchmakeTimer.Start();
                        });
                    }


                    // -----------------------------------------
                    // 同時接続数出力
                    // -----------------------------------------
                    if (generateSessionCntTimer.Timeup())
                    {
                        var now      = DateTime.UtcNow;
                        var areaName = Settings.MatchingArea.ToString();

                        var total     = 0;
                        var breakDown = "{";
                        foreach (var cnt in WatchDogSession.ClientCounts)
                        {
                            total += cnt.Value;

                            breakDown += $"{cnt.Key}:{cnt.Value},";
                        }
                        breakDown += "}";

                        var currentSessionCount                     = new CurrentSessionCount(Settings.MatchingArea);
                        currentSessionCount.Model.areaName          = areaName;
                        currentSessionCount.Model.count             = total;
                        currentSessionCount.Model.date              = now;
                        currentSessionCount.Model.breakDown         = breakDown;
                        currentSessionCount.Model.enabledMatchesCnt = enabledMatchesCnt;
                        currentSessionCount.Model.entriedPlayersCnt = entriedPlayersCnt;
                        await currentSessionCount.SaveAsync(
                            TimeSpan.FromMilliseconds(generateSessionCntTimer.Interval * 2)
                            );

                        if (LogSessionCntTimer.Timeup())
                        {
                            Logger.Logging(
                                new LogObj().AddChild(new LogModels.CurrentSessionCount
                            {
                                AreaName          = areaName,
                                Count             = total,
                                BreakDown         = breakDown,
                                Date              = now,
                                entriedPlayersCnt = entriedPlayersCnt,
                                enabledMatchesCnt = enabledMatchesCnt,
                            })
                                );

                            LogSessionCntTimer.Start();
                        }

                        generateSessionCntTimer.Start();
                    }

                    await Task.Delay(100);
                }
            });
        }