Пример #1
0
        public override async Task <MarkAsReadMailsReply> MarkAsReadMails(MarkAsReadMailsRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new MarkAsReadMailsReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var reply = new MarkAsReadMailsReply();
                reply.Code = ErrorCode.Success;
                if (await MailBox.MarkAsReadMails(session.player_id, request.MessageIds.ToList()) == false)
                {
                    reply.Code = ErrorCode.WrongParam;
                }

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetMailItems {ex.ToString()}");

                return(new MarkAsReadMailsReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #2
0
        /// <summary>
        /// 게임 시작 취소
        /// </summary>
        /// <param name="request"></param>
        /// <param name="responseStream"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task CancelStartPlay(CancelStartPlayRequest request, IServerStreamWriter <CancelStartPlayReply> responseStream, ServerCallContext context)
        {
            try
            {
                Log.Information("StartPlay {0}", context.Peer);

                var session = await context.GetSession();

                if (session == null)
                {
                    await responseStream.WriteAsync(new CancelStartPlayReply()
                    {
                        Code = ErrorCode.LostSession
                    });

                    return;
                }

                //await SequentialMatchmaking.CancelStartPlay(session, responseStream);
            }
            catch (Exception ex)
            {
                Log.Error($"CancelStartPlay error {ex.ToString()}");
            }
        }
Пример #3
0
        public override async Task <GetMailsReply> GetMails(GetMailsRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetMailsReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                long?            NextPageKey = request.NextPageKey != string.Empty ? (long?)long.Parse(request.NextPageKey) : null;
                List <MailState> States      = request.States.Count != 0 ? request.States.Select(x => (MailState)System.Enum.Parse(typeof(MailState), x)).ToList() : null;

                var reply = new GetMailsReply();
                reply.Mails = await MailBox.GetMails(session.member_no, session.user_no, request.Count, NextPageKey, States);

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetMailItems {ex.ToString()}");

                return(new GetMailsReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #4
0
        public override async Task SelectFirstCharacter(SelectFirstCharacterRequest request, IServerStreamWriter <SelectFirstCharacterReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            var user = await UserCache.GetUser(session.member_no, session.user_no, false);

            if (session == null || user == null)
            {
                await responseStream.WriteAsync(new SelectFirstCharacterReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            if (session.character_no != 0 || user.character_no != 0)
            {
                await responseStream.WriteAsync(new SelectFirstCharacterReply()
                {
                    Code = ErrorCode.NotAvailable
                });

                return;
            }

            if (!ACDC.CharacterSelectData[1].CharacterId.Contains(request.CharacterId))
            {
                await responseStream.WriteAsync(new SelectFirstCharacterReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            var character = await CharacterManager.InsertCharacter(session.member_no, session.user_no, session.user_name, session.player_id, request.CharacterId);

            if (character == null)
            {
                await responseStream.WriteAsync(new SelectFirstCharacterReply()
                {
                    Code = ErrorCode.NotAvailable
                });

                return;
            }
            await UserCache.UpdateUserLock(session, session.user_no, character.character_no);

            await Session.UpdateSessionLock(session.session_id, delegate(Session s) { s.character_no = character.character_no; });

            History.Info(session.member_no, session.user_no, session.character_no, HistoryLogAction.GainItem, (byte)HistoryLogReason.SelectCharacter, character.character_type, 1, "", "");
            _ = LogProxy.writeActionLog(session, "캐릭터", "최초획득", character.character_type.ToString()).ConfigureAwait(false);

            await responseStream.WriteAsync(new SelectFirstCharacterReply()
            {
                Code = ErrorCode.Success, CharacterInfo = CharacterManager.CreateCharacterInfo(character, ACDC.CharacterData[character.character_type])
            });
        }
Пример #5
0
        public override async Task <GameService.GetGameEventsReply> GetGameEvents(GetGameEventsRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetGameEventsReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var events = await GameEventQuery.Gets(session.member_no, session.user_no);

                // 이벤트 초기화
                if (events.Count == 0)
                {
                    var nextDate = DateTime.UtcNow.AddDays(1).Date;
                    var endTime  = new DateTime(nextDate.Year, nextDate.Month, nextDate.Day, 0, 0, 0, DateTimeKind.Utc);

                    var game_event = new Models.GameEvent()
                    {
                        user_no  = session.user_no,
                        event_id = 1,
                        reward   = 0,
                        occ_time = endTime,
                    };
                    events.Add(game_event);
                    await GameEventQuery.Add(session.member_no, game_event);
                }

                // 이벤트 목록 생성
                var reply = new GetGameEventsReply();
                reply.Code = ErrorCode.Success;
                foreach (var game_event in events)
                {
                    reply.Events.Add(new EventInfo()
                    {
                        EventId         = game_event.event_id,
                        IsReward        = (game_event.reward == 0 ? false : true),
                        RewardStartTime = DateTime.SpecifyKind(game_event.occ_time, DateTimeKind.Utc).ToTimestamp(),
                        RewardItemId    = (int)GameItemId.OpenEventBox,
                    });
                }

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetGameEvents {ex.ToString()}");

                return(new GetGameEventsReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
        protected SessionEntity SessionFromContext(ServerCallContext context)
        {
            var session = context.GetSession();

            if (session == null)
            {
                throw new UnAuthorizedException($"Cannot find session by token. Method: {context.Method}");
            }

            return(session);
        }
Пример #7
0
        public override async Task <GameService.GetAdvertisementRewardsReply> GetAdvertisementRewards(GetAdvertisementRewardsRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetAdvertisementRewardsReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var rewards = await AdvertisementRewardQuery.Gets(session.member_no, session.user_no);

                var currentTime = DateTime.UtcNow;
                var reply       = new GetAdvertisementRewardsReply();
                reply.Code = ErrorCode.Success;
                foreach (var reward in rewards)
                {
                    var adData = ACDC.AdListData[reward.advertisement_id];
                    if (adData == null || adData == default(JAdListData))
                    {
                        continue;
                    }

                    if (core.MathHelpers.GetResetTime(adData.ResetTime, reward.occ_time) != core.MathHelpers.GetResetTime(adData.ResetTime, currentTime))
                    {
                        continue;
                    }

                    reply.AdvertisementRewards.Add(new AdvertisementRewardInfo()
                    {
                        AdvertisementId = reward.advertisement_id,
                        RewardCount     = reward.reward,
                    });
                }

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetGameEvents {ex.ToString()}");

                return(new GetAdvertisementRewardsReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #8
0
        public override async Task <GetRankListReply> GetRankList(GetRankListRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetRankListReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }


                var rankList = await Ranking.GetRankList(session.player_id, request.Info, request.From, request.To, request.ReadMy, request.CharacterId, request.WithoutProperty);

                var reply = new GetRankListReply()
                {
                    Code          = ErrorCode.Success,
                    Cardinality   = rankList.cardinality,
                    NextResetTime = rankList.nextResetTime,
                    MyRank        = request.ReadMy ? rankList.myRank : 0,
                    MyScore       = request.ReadMy ? rankList.myScore : 0,
                };

                foreach (var rank in rankList.scores)
                {
                    reply.Scores.Add(new ScoreInfo()
                    {
                        Rank  = rank.rank,
                        Score = rank.score,
                        Name  = rank.property != null && rank.property.ContainsKey("Name") ? rank.property["Name"] : string.Empty
                    });
                }

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetRankList {ex.ToString()}");

                return(new GetRankListReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #9
0
        public override async Task <GetScoreListReply> GetScoreList(GetScoreListRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetScoreListReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var scoreList = await Ranking.GetScoreList(request.Info, request.WithoutProperty, request.PlayerIds.ToList());

                var reply = new GetScoreListReply()
                {
                    Code        = ErrorCode.Success,
                    Cardinality = scoreList.cardinality,
                    SortingType = scoreList.sortingType
                };

                foreach (var score in scoreList.scores)
                {
                    reply.Scores.Add(new ScoreInfo()
                    {
                        Rank  = score.rank,
                        Score = score.score,
                        Name  = request.WithoutProperty ? string.Empty : score.property["name"]
                    });
                }

                return(new GetScoreListReply()
                {
                    Code = ErrorCode.Success
                });
            }
            catch (Exception ex)
            {
                Log.Error($"GetScoreList {ex.ToString()}");

                return(new GetScoreListReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #10
0
        public override async Task <GetRankReply> GetRank(GetRankRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetRankReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }


                var rank = await Ranking.GetRank(session.player_id, request.Info, request.CharacterId);

                if (rank == null)
                {
                    return(new GetRankReply()
                    {
                        Code = ErrorCode.NotExist
                    });
                }


                return(new GetRankReply()
                {
                    Code = ErrorCode.Success,
                    Rank = rank.rank,
                    Score = rank.score,
                    Cardinality = rank.cardinality,
                    Highscore = rank.highscore
                });
            }
            catch (Exception ex)
            {
                Log.Error($"GetRank {ex.ToString()}");

                return(new GetRankReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #11
0
        /// <summary>
        /// 미션 그룹(or Base) 보상
        /// </summary>
        /// <param name="request"></param>
        /// <param name="responseStream"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GetRewardMissionBase(GetRewardMissionBaseRequest request, IServerStreamWriter <GetRewardMissionBaseReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new GetRewardMissionBaseReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            var ret = await MissionManager.RewardBase(session, request.MissonBaseId);

            await responseStream.WriteAsync(ret);
        }
Пример #12
0
        public override async Task BuyItem(BuyItemRequest request, IServerStreamWriter <BuyItemReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new BuyItemReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            var reply = new BuyItemReply();

            (reply.Code, reply.Item, reply.AccountGoods) = await ShopManager.BuyItem(session, request.ShopItemId, request.ShopId);

            await responseStream.WriteAsync(reply);
        }
Пример #13
0
        //////////////////////////////////////////////
        /// Ranking
        public override async Task <GetLeaderboardReply> GetLeaderboard(GetLeaderboardRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetLeaderboardReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var leaderboard = await Ranking.GetInfo(request.Info);

                return(new GetLeaderboardReply()
                {
                    Code = ErrorCode.Success,
                    Season = new Season()
                    {
                        Type = leaderboard.season.type,
                        ResetDay = leaderboard.season.resetDay,
                        ResetHour = leaderboard.season.resetHour,
                        BeginTime = leaderboard.season.beginTime,
                        EndTime = leaderboard.season.endTime,
                        NextResetTime = leaderboard.season.nextResetTime,
                        Seq = leaderboard.season.seq,
                    }
                });
            }
            catch (Exception ex)
            {
                Log.Error($"GetLeaderboard {ex.ToString()}");

                return(new GetLeaderboardReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #14
0
        public override async Task <PurchaseInAppReplay> PurchaseInApp(PurchaseInAppRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new PurchaseInAppReplay()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var(validated, receiptChecker) = await InAppPurchase.IsValidPurchase(request);

                if (validated == false || receiptChecker == null)
                {
                    return(new PurchaseInAppReplay()
                    {
                        Code = ErrorCode.WrongParam
                    });
                }

                // todo : ProductId로 상점 아이템을 찾아 구매 처리함  (receiptChecker.ProductId)

                var reply = new PurchaseInAppReplay();
                (reply.Code, reply.Item, reply.AccountGoods) = await ShopManager.BuyItem(session, 34, 4);

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"PurchaseInApp {ex.ToString()}");

                return(new PurchaseInAppReplay()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #15
0
        /// <summary>
        /// 미션 정보 얻기
        /// 접속, 게임 종료, 미션창 활성중 리셋, 리셋이후 첫 미션창 오픈, 기타 로비에서 미션 조건 만족시
        /// </summary>
        /// <param name="request"></param>
        /// <param name="responseStream"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GetMission(GetMissionRequest request, IServerStreamWriter <GetMissionReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new GetMissionReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            var missions = await MissionManager.GetMissionsLock(session);

            await responseStream.WriteAsync(new GetMissionReply()
            {
                Code = ErrorCode.Success, UserMissions = missions
            });
        }
Пример #16
0
        public override async Task UpgradePowerLevel(UpgradePowerLevelRequest request, IServerStreamWriter <UpgradePowerLevelReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new UpgradePowerLevelReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            var(ret, goods, character_info) = await CharacterGrowth.UpgradePowerLevel(session, request.CharacterId);

            await responseStream.WriteAsync(new UpgradePowerLevelReply()
            {
                Code = ret, AccountGoods = goods, CharacterLevel = character_info.CharacterLevel, CharacterPiece = character_info.CharacterPiece
            });
        }
Пример #17
0
        public override async Task SelectCharacter(SelectCharacterRequest request, IServerStreamWriter <SelectCharacterReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new SelectCharacterReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            bool checkSelectCharacter = await session.SelectCharacter(request.CharacterId);

            if (checkSelectCharacter == false)
            {
                await responseStream.WriteAsync(new SelectCharacterReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            if (request.CharacterId != session.character_type)
            {
                await UserCache.UpdateUserLock(session, session.user_no, session.character_no);
            }

            await session.UpdateSessionLock(request.CharacterId, session.map_id, false);


            await responseStream.WriteAsync(new SelectCharacterReply()
            {
                Code = ErrorCode.Success
            });
        }
Пример #18
0
        public override async Task <SelectMapReply> SelectMap(SelectMapRequest request, ServerCallContext context)
        {
            SelectMapReply reply = new SelectMapReply()
            {
                Code = ErrorCode.WrongParam
            };

            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    reply.Code = ErrorCode.LostSession;
                    return(reply);
                }

                if (request.MapId == session.map_id || ACDC.MapData[request.MapId] == null)
                {
                    return(reply);
                }

                await using (var user = await UserCache.GetUser(session.member_no, session.user_no, true, true, false))
                {
                    user.map_id  = (byte)request.MapId;
                    user.IsDirty = true;
                }

                await session.UpdateSessionLock(session.character_type, request.MapId, false);

                reply.Code = ErrorCode.Success;
            }
            catch (Exception ex)
            {
                Log.Error($"GetRewardEvent {ex.ToString()}");
            }
            return(reply);
        }
Пример #19
0
        public override async Task <GetMailItemsReply> GetMailItems(GetMailItemsRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetMailItemsReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var reply = new GetMailItemsReply();
                reply.Item         = new ItemList();
                reply.AccountGoods = new Goods();
                bool ret = false;
                (ret, reply.Item, reply.AccountGoods) = await MailBox.GetMailItems(session, request.MessageIds.ToList(), request.CharacterId);

                if (ret == false)
                {
                    reply.Code = ErrorCode.NotExist;
                }

                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetMailItems {ex.ToString()}");

                return(new GetMailItemsReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #20
0
        public override async Task <GameService.DebugCommandReply> DebugCommand(DebugCommandRequest request, ServerCallContext context)
        {
            if (ServerConfiguration.Instance.EnableDebugCommand == false)
            {
                return(new DebugCommandReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }

            Log.Information($"DebugCommand {request.Cmd}, {request.Param1}, {request.Param2}, {request.Param3}, {request.Param4}");

            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new DebugCommandReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                return(await Lobby.DebugCommand.Execute(session, request.Cmd, request.Param1, request.Param2, request.Param3, request.Param4));
            }
            catch (Exception ex)
            {
                Log.Error($"DebugCommand {ex.ToString()}");

                return(new DebugCommandReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
        public static async Task StartPlay(StartPlayRequest request, IServerStreamWriter <StartPlayReply> responseStream, ServerCallContext context)
        {
            Log.Information($"StartPlay mapId:{request.MapId}, SelectedCharacter:{request.SelectedCharacter}, IsImmediatelyJoin{request.IsImmediatelyJoin}");

            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            // 게임 시작 요청 정보를 캐싱
            await session.UpdateSessionLock(request.SelectedCharacter, request.MapId, true);

            if (request.IsImmediatelyJoin)
            {
                (bool ret, string server_addr, byte worldId, string channel_key, string channel_id) = await Channel.GetAvailableServer(request.MapId);

                if (ret == false)
                {
                    // 전투 가능한 서버가 없다
                    Log.Error($"Cannot find Server user_no:{session.user_no}");
                    await responseStream.WriteAsync(new StartPlayReply()
                    {
                        Code = ErrorCode.BusyServer
                    });

                    return;
                }

                var tmp_players = new Dictionary <string, ServerCommon.PlayerInfo>();
                ServerCommon.PlayerInfo player = new ServerCommon.PlayerInfo()
                {
                    user_no        = session.user_no,
                    character_type = session.character_type,
                    user_id        = session.user_name,
                    team           = (byte)core.MathHelpers.GetRandomInt((int)core.BaseStruggleTeam.TeamCount),
                };
                tmp_players.Add(session.session_id, player);

                var characters = new List <StartPlayCharacterInfo>();
                characters.Add(new StartPlayCharacterInfo()
                {
                    SelectedCharacter = session.character_type, UserId = session.user_name, Team = player.team
                });
                var reply = new StartPlayReply()
                {
                    Code             = ErrorCode.Success,
                    IsStart          = true,
                    BattleServerAddr = server_addr,
                    WorldId          = worldId,
                    MapId            = request.MapId,
                };
                characters.ForEach(x => reply.CharacterList.Add(x));

                await responseStream.WriteAsync(reply);


                await SequentialMatchmaking.PubStartPlay(tmp_players, worldId, channel_id, session);


#pragma warning disable 4014
                Task.Run(async() => await SequentialMatchmaking.WaitGameResult(channel_id));
#pragma warning restore 4014

                return;
            }

            // 다른 플레이어로 인해 매칭이 시작 되었는지 확인
            if ((await SequentialMatchmaking.RestoreMatchUser(session.user_no, responseStream)) == true)
            {
                return;
            }

            // 대기중이 플레이어 찾기
            (var player_list, var players, var character_list, var search_success) = await SequentialMatchmaking.SearchPlayer(session, request);

            if (search_success == true)
            {
                // 게임 시작
                if ((await SequentialMatchmaking.StartPlay(player_list, players, character_list, session, request, responseStream)) == false)
                {
                    // 예약했던 플레이어 취소
                    await SequentialMatchmaking.ClearReservedPlayer(player_list);
                }
                return;
            }

            // 예약했던 플레이어 취소
            await SequentialMatchmaking.ClearReservedPlayer(player_list);

            Log.Information("StartPlay waiting... {0}", session.user_no);

            // 대기
            await SequentialMatchmaking.WaitStartPlay(session, request, responseStream);
        }
        public static async Task StartPlay(StartPlayRequest request, IServerStreamWriter <StartPlayReply> responseStream, ServerCallContext context)
        {
            var mapData = ACDC.MapData[request.MapId];

            if (mapData == null)
            {
                Log.Warning($"StartPlay error map id {request.MapId}");
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            var gameModeData = ACDC.GameModeData[mapData.GameMode];

            if (gameModeData == null)
            {
                Log.Warning($"StartPlay error mode {mapData.GameMode}");
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            MinimumStartPlay minimumStartPlay;

            minimumStartPlayMap.TryGetValue(request.MapId, out minimumStartPlay);

            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            Log.Information($"StartPlay user_no:{session.user_no}, user_name:{session.user_name}, mapId:{request.MapId}, SelectedCharacter:{request.SelectedCharacter}, IsImmediatelyJoin{request.IsImmediatelyJoin}");

            bool checkSelectCharacter = await session.SelectCharacter(request.SelectedCharacter);

            if (checkSelectCharacter == false)
            {
                Log.Warning($"StartPlay error character id {request.SelectedCharacter}");
                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code = ErrorCode.WrongParam
                });

                return;
            }

            bool IsAISwitch     = false;
            bool IsFirstRequest = false;
            bool IsWaitingUser  = await WaitingList.IsWaitingUser(session.user_no);

            bool IsMatchTimeout = false;

            // 이미 대기중이 였지만 요청이 달라진 경우,  최초 요청으로 판단
            if (IsWaitingUser == false || session.IsChangeRequest(request))
            {
                IsFirstRequest = true;
                History.Info(session.member_no, session.user_no, session.character_no, HistoryLogAction.TryStartPlay, (byte)HistoryLogReason.None, request.SelectedCharacter, request.MapId, "", "");
                _ = LogProxy.writeActionLog(session, "플레이", "매칭시도", request.MapId.ToString()).ConfigureAwait(false);
            }
            else
            {
                if (DateTime.UtcNow > session.first_request_time.AddMilliseconds(ServerConfiguration.Instance.gameSetting.AIMatchTime))
                {
                    IsMatchTimeout = true;
                    if (ServerConfiguration.Instance.gameSetting.EnableAIMatch == true)
                    {
                        IsAISwitch = true;
                    }
                }

                if (minimumStartPlay != null &&
                    minimumStartPlay.Enable &&
                    DateTime.UtcNow > session.first_request_time.AddSeconds(minimumStartPlay.Timeout))
                {
                    Log.Information($"matchTimeout first_request_time:{session.first_request_time}, now:{DateTime.UtcNow}, timeout:{session.first_request_time.AddSeconds(minimumStartPlay.Timeout)}");
                    IsMatchTimeout = true;
                }
            }

            Log.Information($"flag IsAISwitch:{IsAISwitch}, IsFirstRequest:{IsFirstRequest}, IsWaitingUser{IsWaitingUser}, IsMatchTimeout{IsMatchTimeout}");


            if (request.SelectedCharacter != session.character_type || request.MapId != session.map_id)
            {
                var user = await UserCache.GetUser(session.member_no, session.user_no, false);

                user.character_no = session.character_no;
                user.map_id       = (byte)request.MapId;
                user.IsDirty      = true;
            }

            // 게임 시작 요청 정보를 캐싱
            await session.UpdateSessionLock(request.SelectedCharacter, request.MapId, IsFirstRequest);

            if (request.IsImmediatelyJoin)
            {
                await StartPlaySimulate(request, responseStream, context, session, mapData, gameModeData);

                return;
            }

            long match_id = await MatchInstanceId.GetMatchInstanceId();

            if ((await MatchUser.OccupyMatchUser(session.user_no, match_id)) == false)
            {
                // 다른 플레이어로 인해 매칭이 완료 되었는지 확인
                if ((await RestoreMatchUser(session, responseStream)) == true)
                {
                    if (ServerConfiguration.Instance.gameSetting.EnableReJoin == false)
                    {
                        // 재입장이 불가하면, 게임 시작 직후 매칭 정보 삭제
                        await MatchUser.RemoveMatchUser(session.user_no);
                    }
                    return;
                }
                else
                {
                    await responseStream.WriteAsync(new StartPlayReply()
                    {
                        Code             = ErrorCode.NotEnough,
                        IsStart          = false,
                        BattleServerAddr = "",
                        WorldId          = 0,
                        MapId            = request.MapId,
                    });

                    return;
                }
            }

            if (request.IsCancel)
            {
                // 대기 목록에서 제거
                await WaitingList.RemoveWaitingUser(session.user_no);

                await MatchUser.RemoveMatchUser(session.user_no);


                await responseStream.WriteAsync(new StartPlayReply()
                {
                    Code             = ErrorCode.NotEnough,
                    IsStart          = false,
                    BattleServerAddr = "",
                    WorldId          = 0,
                    MapId            = request.MapId,
                });

                return;
            }

            // 대기중이 플레이어 찾기
            (var matchResult, var search_success) = await SearchPlayer(session, match_id, mapData, gameModeData);

            if (search_success == false && IsAISwitch == true)
            {
                // 부족한 인원 만큼 AI로 채워 넣는다.(자신은 제외)
                int cnt = (GetStartPlayerCount(gameModeData) - 1) - matchResult.replyToClient.CharacterList.Count;
                for (int i = 0; i < cnt; ++i)
                {
                    matchResult.AddAI(session, mapData, gameModeData);
                }
            }

            if (search_success == true || IsAISwitch == true ||
                (ServerConfiguration.Instance.gameSetting.MatchForce && IsMatchTimeout) ||
                (minimumStartPlay != null && minimumStartPlay.Enable && IsMatchTimeout && matchResult.replyToClient.CharacterList.Count + 1 >= minimumStartPlay.PlayerCount)
                )
            {
                // 게임 시작
                if ((await StartPlay(match_id, session, request, responseStream, matchResult, mapData, gameModeData)) == false)
                {
                    // 예약했던 플레이어 취소
                    await MatchUser.CancelOccupiedMatchUser(matchResult.replyToBattleServer.players);
                }
                else
                {
                    if (ServerConfiguration.Instance.gameSetting.EnableReJoin == false)
                    {
                        // 재입장이 불가하면, 게임 시작 직후 매칭 정보 삭제
                        await MatchUser.RemoveMatchUser(session.user_no);
                    }
                }
                return;
            }

            // 예약했던 플레이어 취소
            await MatchUser.CancelOccupiedMatchUser(matchResult.replyToBattleServer.players);

            Log.Information("StartPlay waiting... {0}", session.user_no);

            // 대기
            await WaitStartPlay(session, request, responseStream);

            // 검색 실패시 다음 검색 조건 범위를 넓힌다.
            await session.WideningRangeRankLock();

            // 실패 결과 리턴
            matchResult.replyToClient.Code    = ErrorCode.NotEnough;
            matchResult.replyToClient.IsStart = false;
            matchResult.replyToClient.CharacterList.Add(new StartPlayCharacterInfo()); // 자신포함으로 빈슬롯 한개 넣어줌
            await responseStream.WriteAsync(matchResult.replyToClient);
        }
Пример #23
0
        public override async Task <GameService.RewardAdvertisementReply> RewardAdvertisement(RewardAdvertisementRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new RewardAdvertisementReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }

                var adData = ACDC.AdListData[request.AdvertisementId];
                if (adData == null || adData == default(JAdListData))
                {
                    return(new RewardAdvertisementReply()
                    {
                        Code = ErrorCode.WrongParam
                    });
                }

                bool is_insert = false;

                var reply = new RewardAdvertisementReply();
                reply.AccountGoods = new Goods();
                reply.Item         = new ItemList();
                var currentTime = DateTime.UtcNow;
                int RewardCount = 0;
                await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
                {
                    var rewards = await AdvertisementRewardQuery.Gets(session.member_no, session.user_no);

                    var reward = rewards.Where(x => x.advertisement_id == request.AdvertisementId).FirstOrDefault();
                    if (reward == null || reward == default(Models.AdvertisementReward))
                    {
                        is_insert = true;
                        reward    = new AdvertisementReward()
                        {
                            user_no          = session.user_no,
                            advertisement_id = adData.Id,
                            reward           = 0,
                            occ_time         = currentTime,
                        };
                    }
                    else
                    {
                        // refresh
                        if (core.MathHelpers.GetResetTime(adData.ResetTime, reward.occ_time) != core.MathHelpers.GetResetTime(adData.ResetTime, currentTime))
                        {
                            reward.occ_time = currentTime;
                            reward.reward   = 0;
                        }
                    }

                    if (reward.reward >= adData.ViewLimit)
                    {
                        return(new RewardAdvertisementReply()
                        {
                            Code = ErrorCode.OverLimit
                        });
                    }

                    // 보상 지급
                    await using (var user = await UserCache.GetUser(session.member_no, session.user_no, true, true, false))
                        await using (var character = await CharacterCache.Instance.GetEntity(session.member_no, session.character_no, true, true, false))
                        {
                            await Inventory.Insert(session, user, character, adData.ItemId, adData.Count, new LogReason("A_AD", adData.Id.ToString()), reply.Item, null, adData.Id.ToString());

                            reply.AccountGoods.Set(user);
                        }

                    ++reward.reward;
                    RewardCount     = reward.reward;
                    reward.occ_time = currentTime;
                    if (is_insert)
                    {
                        await AdvertisementRewardQuery.Add(session.member_no, reward);
                    }
                    else
                    {
                        await AdvertisementRewardQuery.Update(session.member_no, reward);
                    }

                    _ = LogProxy.writeActionLog(session, "광고시청", "광고", adData.Id.ToString()).ConfigureAwait(false);
                }

                reply.Code            = ErrorCode.Success;
                reply.RewardCount     = RewardCount;
                reply.AdvertisementId = request.AdvertisementId;
                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetRewardEvent {ex.ToString()}");

                return(new RewardAdvertisementReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #24
0
        public override async Task <GameService.GetRewardEventReply> GetRewardEvent(GetRewardEventRequest request, ServerCallContext context)
        {
            try
            {
                var session = await context.GetSession();

                if (session == null)
                {
                    return(new GetRewardEventReply()
                    {
                        Code = ErrorCode.LostSession
                    });
                }


                var reply = new GetRewardEventReply();
                reply.AccountGoods = new Goods();
                reply.Item         = new ItemList();
                await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
                {
                    var events = await GameEventQuery.Gets(session.member_no, session.user_no);

                    var gameEvent = events.Where(x => x.event_id == request.EventId).FirstOrDefault();
                    if (gameEvent == null || gameEvent == default(Models.GameEvent))
                    {
                        return(new GetRewardEventReply()
                        {
                            Code = ErrorCode.NotExist
                        });
                    }

                    if (gameEvent.reward != 0)
                    {
                        return(new GetRewardEventReply()
                        {
                            Code = ErrorCode.AlreadyReward
                        });
                    }

                    if (gameEvent.occ_time > DateTime.UtcNow)
                    {
                        return(new GetRewardEventReply()
                        {
                            Code = ErrorCode.NotEnough
                        });
                    }

                    // 보상 지급
                    await using (var user = await UserCache.GetUser(session.member_no, session.user_no, true, true, false))
                        await using (var character = await CharacterCache.Instance.GetEntity(session.member_no, session.character_no, true, true, false))
                        {
                            await Inventory.Insert(session, user, character, (int)GameItemId.OpenEventBox, 1, new LogReason("A_EVENT", gameEvent.event_id.ToString()), reply.Item);

                            reply.AccountGoods.Set(user);
                        }

                    gameEvent.reward = 1;
                    await GameEventQuery.Update(session.member_no, gameEvent);
                }

                reply.Code = ErrorCode.Success;
                return(reply);
            }
            catch (Exception ex)
            {
                Log.Error($"GetRewardEvent {ex.ToString()}");

                return(new GetRewardEventReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }
        }
Пример #25
0
        public override async Task GetUserInfo(GetUserInfoRequest request, IServerStreamWriter <GetUserInfoReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new GetUserInfoReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            UserInfo userInfo = new UserInfo();
            await userInfo.Load(session);

            Dictionary <string, object> properties = new Dictionary <string, object>();

            properties.Add("Name", userInfo.UserName);
            await Ranking.PutProperty(session.player_id, string.Empty, properties);

            //await Ranking.ProcessRankingReward(session);



            var member = await MemberQuery.GetMember(session.player_id);

            // todo : member.last_play_time 체크로 지급 여부 판단
            var currentTime = DateTime.UtcNow;

            var mails = await MailQuery.GetSystemMail(member.last_play_time);

            foreach (var mail in mails)
            {
                if (mail.recipient != string.Empty)
                {
                    // 받는 사람 목록이 있는 경우 해당 player_id 가 맞는지 비교
                    string[] words = mail.recipient.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    if (words.Contains(member.player_id) == false)
                    {
                        continue;
                    }
                }

                var m = new Mail();
                switch (member.language_code)
                {
                case "ko":
                    m.title = mail.title_ko;
                    m.body  = mail.body_ko;
                    break;

                default:
                    m.title = mail.title_en;
                    m.body  = mail.body_en;
                    break;
                }
                m.mail_state = MailState.Send;
                if (mail.item_id != 0 && mail.item_count > 0)
                {
                    m.has_item = true;
                }
                m.item_id     = mail.item_id;
                m.item_count  = mail.item_count;
                m.sender      = mail.sender;
                m.send_time   = currentTime;
                m.expiry_time = currentTime.AddDays(mail.expiry_days);
                m.user_no     = member.user_no;

                await MailQuery.SendMail(member.member_no, m);
            }

            // member.last_play_time 현재 시간으로 기록
            await MemberQuery.UpdateMemberLastPlayTime(session.member_no, currentTime);

            await responseStream.WriteAsync(new GetUserInfoReply()
            {
                Code = ErrorCode.Success,
                User = userInfo,
            });
        }
Пример #26
0
        public override async Task ChangeUserName(ChangeUserNameRequest request, IServerStreamWriter <ChangeUserNameReply> responseStream, ServerCallContext context)
        {
            var session = await context.GetSession();

            if (session == null)
            {
                await responseStream.WriteAsync(new ChangeUserNameReply()
                {
                    Code = ErrorCode.LostSession
                });

                return;
            }

            //유저 아이디 영문과 숫자 조합만 허용
            //if (Regex.IsMatch(request.UserName, @"^[a-zA-Z0-9]+$") == false)
            if (Regex.IsMatch(request.UserName, @"^[a-zA-Z0-9가-힣]*$") == false)
            {
                Log.Error($"ChangeUserName error {request.UserName}");
                await responseStream.WriteAsync(new ChangeUserNameReply()
                {
                    Code = ErrorCode.WrongLetters
                });

                return;
            }

            if (request.UserName.Length < 2 || request.UserName.Length > 10)
            {
                Log.Error($"ChangeUserName error {request.UserName}");
                await responseStream.WriteAsync(new ChangeUserNameReply()
                {
                    Code = ErrorCode.WrongLetters
                });

                return;
            }

            if (request.UserName.IsLetterOrDigit() == false)
            {
                Log.Error($"ChangeUserName error {request.UserName}");
                await responseStream.WriteAsync(new ChangeUserNameReply()
                {
                    Code = ErrorCode.WrongLetters
                });

                return;
            }

            if (await BannedWordFilter.Check(request.UserName) == false)
            {
                Log.Error($"ChangeUserName error {request.UserName}");
                await responseStream.WriteAsync(new ChangeUserNameReply()
                {
                    Code = ErrorCode.WrongLetters
                });

                return;
            }

            // 유저 디비 업데이트
            var ret = await MemberQuery.UpdateMember(session.member_no, request.UserName);

            if (ret != ErrorCode.Success)
            {
                await responseStream.WriteAsync(new ChangeUserNameReply()
                {
                    Code = ret
                });

                return;
            }


            // 세션 캐시 업데이트
            await Session.UpdateSessionLock(session.session_id, delegate(Session s) { s.user_name = request.UserName; });

            await responseStream.WriteAsync(new ChangeUserNameReply()
            {
                Code = ErrorCode.Success
            });
        }