public static async Task <RedLock> CreateLockAsync(string key)
        {
            var redLock = new RedLock();
            await redLock.LockAsync(key);

            return(redLock);
        }
Exemple #2
0
        /// <summary>
        /// 미션 정보 얻기
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        public static async Task <UserMissions> GetMissionsLock(Session session)
        {
            var userMissions = new UserMissions();
            List <Models.Mission> missions;

            missions = await MissionCache.Instance.GetEntities(session.member_no, session.user_no, true);

            if (await Refresh(missions, session, true))
            {
                await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
                {
                    missions = await MissionCache.Instance.GetEntities(session.member_no, session.user_no, true);
                    await Refresh(missions, session, false);
                }
            }

            if (missions.Count > 0)
            {
                foreach (var mission in missions)
                {
                    var mission_base = new MissionBaseInfo();
                    foreach (var m in mission.Missions())
                    {
                        mission_base.Add(((ValueTuple <int, int, bool, int>)m).Item1, ((ValueTuple <int, int, bool, int>)m).Item2, ((ValueTuple <int, int, bool, int>)m).Item3);
                    }

                    mission_base.MissionBaseId     = mission.mission_base_id;
                    mission_base.MissionBaseReward = mission.mission_reward;

                    userMissions.MissionBaseList.Add(mission_base);
                }
            }

            return(userMissions);
        }
        public static async Task <(ErrorCode, Goods, CharacterInfo)> UpgradePowerLevel(Session session, int character_id)
        {
            var character_data = ACDC.CharacterData[character_id];

            if (character_data == null || character_data == default(JCharacterData))
            {
                Log.Information($"UpgradePowerLevel cannot find character_id:{character_id}, user_name:{session.user_name}");
                return(ErrorCode.WrongParam, null, null);
            }

            var           level_table    = character_data.LevelTable;
            var           goods          = new Goods();
            CharacterInfo character_info = null;

            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
            {
                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.user_no, character_id, true, true, false))
                    {
                        if (character == null || character == default(Models.Character))
                        {
                            Log.Information($"UpgradePowerLevel cannot find character_id:{character_id}, user_name:{session.user_name}");
                            return(ErrorCode.WrongParam, null, null);
                        }

                        JPowerLevel_TableData power_level_data;
                        if (level_table.TryGetValue(character.character_level, out power_level_data) == false)
                        {
                            return(ErrorCode.OverLimit, null, null);
                        }

                        if (character.piece < power_level_data.Req_Piece)
                        {
                            return(ErrorCode.NotEnough, null, null);
                        }

                        if (Inventory.UseGoods(session, user, power_level_data.Pricetype, power_level_data.Req_PriceValue, new LogReason("S_UPGRADE_SMASHER", character_id.ToString())) == false)
                        {
                            return(ErrorCode.NotEnough, null, null);
                        }

                        character.piece           -= power_level_data.Req_Piece;
                        character.character_level += 1;
                        character.IsDirty          = true;

                        goods.Set(user);

                        character_info = CharacterManager.CreateCharacterInfo(character, character_data);

                        var game_item_data = ACDC.GameItemData.Values.Where(x => x.Item_Type == (int)GameItemType.CharacterPiece && x.LinkId == character_id).FirstOrDefault();
                        var item_id        = game_item_data.id;
                        var item_count     = power_level_data.Req_Piece;
                        _ = LogProxy.writeItemLog(session, game_item_data.Item_Type.ToString(), item_id.ToString(), "y", "", item_count, "", 0, 0, "add", "S_UPGRADE_SMASHER", character_id.ToString(), "").ConfigureAwait(false);
                        _ = LogProxy.writeActionLog(session, "캐릭터", "업그레이드", character.character_type.ToString()).ConfigureAwait(false);

                        History.Info(session.member_no, session.user_no, session.character_no, HistoryLogAction.UseItem, (byte)HistoryLogReason.UpgradePowerLevel, item_id, item_count, "", "");
                    }
            }
            return(ErrorCode.Success, goods, character_info);
        }
Exemple #4
0
        /// <summary>
        /// 각 미션 보상
        /// </summary>
        /// <param name="session"></param>
        /// <param name="mission_id"></param>
        /// <returns></returns>
        public static async Task <ErrorCode> Reward(Session session, int mission_id)
        {
            Log.Error($"Mission Reward {mission_id}, {session.user_name}");
            var mission_info_data = ACDC.Mission_infoData[mission_id];

            if (mission_info_data == null || mission_info_data == default(JMission_infoData))
            {
                return(ErrorCode.WrongParam);
            }
            List <Models.Mission> missions;

            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
            {
                missions = await MissionCache.Instance.GetEntities(session.member_no, session.user_no, true);
                await Refresh(missions, session, false);

                if (missions.Count > 0)
                {
                    foreach (var mission in missions)
                    {
                        foreach (var m in mission.Missions())
                        {
                            // 동일 미션 찾기
                            if (((ValueTuple <int, int, bool, int>)m).Item1 == mission_id)
                            {
                                // 조건 달성 체크
                                if (((ValueTuple <int, int, bool, int>)m).Item2 < mission_info_data.Mission_Value)
                                {
                                    return(ErrorCode.NotEnough);
                                }

                                // 보상을 이미 받았는지 체크
                                if (((ValueTuple <int, int, bool, int>)m).Item3 == true)
                                {
                                    return(ErrorCode.AlreadyReward);
                                }

                                // 보상 지급 완료 상태 저장
                                mission.SetReward(((ValueTuple <int, int, bool, int>)m).Item4, true);
                                await MissionCache.Instance.UpdateEntity(session.member_no, mission);

                                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, mission_info_data.Reward_Id, mission_info_data.Reward_Value, new LogReason("A_MISSION", mission_info_data.MissionType.ToString()));
                                    }

                                return(ErrorCode.Success);
                            }
                        }
                    }
                }
            }

            return(ErrorCode.WrongParam);
        }
        public static async Task UpdateSessionLock(string session_id, Action <Session> action)
        {
            // 세션 캐시 업데이트
            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session_id}"))
            {
                // reload
                var session = await Session.GetSession(session_id);

                action(session);
                await Session._UpdateSession(session);
            }
        }
        public static async Task UpdateUserLock(Session session, long user_no, long character_no)
        {
            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
            {
                // 유저 캐시 업데이트
                var user = await UserCache.GetUser(session.member_no, user_no, false);

                if (user != null && user != default(Models.User))
                {
                    user.character_no = character_no;
                    await UserCache.SetUser(user);
                }
                // 유저 디비 업데이트
                await UserQuery.UpdateUser(session.member_no, user_no, character_no);
            }
        }
Exemple #7
0
        public static async Task <UserShops> GetShopLock(Session session)
        {
            var userShops            = new UserShops();
            List <Models.Shop> shops = null;

            shops = await ShopCache.Instance.GetEntities(session.member_no, session.user_no, true);

            if (await Refresh(session, shops, true))
            {
                await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
                {
                    shops = await ShopCache.Instance.GetEntities(session.member_no, session.user_no, true);
                    await Refresh(session, shops, false);
                }
            }

            if (shops.Count > 0)
            {
                foreach (var shop in shops)
                {
                    var shopInfo = userShops.Shops.Where(x => x.ShopId == shop.shop_id).FirstOrDefault();
                    if (shopInfo == null || shopInfo == default(ShopInfo))
                    {
                        shopInfo        = new ShopInfo();
                        shopInfo.ShopId = shop.shop_id;
                        userShops.Shops.Add(shopInfo);
                    }

                    shopInfo.Items.Add(new ShopItemInfo()
                    {
                        ShopItemId    = shop.shop_item_id,
                        Quantity      = shop.quantity,
                        PurchaseCount = shop.purchase_count
                    });
                }
            }

            return(userShops);
        }
Exemple #8
0
        /// <summary>
        /// 미션 그룹(or Base 예 일일, 주간) 보상.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="mission_base_id"></param>
        /// <returns></returns>
        public static async Task <GetRewardMissionBaseReply> RewardBase(Session session, int mission_base_id)
        {
            ItemList itemList     = new ItemList();
            Goods    AccountGoods = new Goods();

            Log.Information($"Mission RewardBase {mission_base_id}, {session.user_name}");
            var mission_base_data = ACDC.Mission_BaseData[mission_base_id];

            if (mission_base_data == null || mission_base_data == default(JMission_BaseData))
            {
                return(new GetRewardMissionBaseReply()
                {
                    Code = ErrorCode.WrongParam
                });
            }

            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
            {
                await using (var mission = await MissionCache.Instance.GetEntity(session.member_no, session.user_no, mission_base_id, true, true, false))
                {
                    // 해당 미션이 리셋 되었는지 확인
                    if (mission.IsAvailable() == false)
                    {
                        return(new GetRewardMissionBaseReply()
                        {
                            Code = ErrorCode.NotEnough
                        });
                    }

                    // 이미 보상을 받았는지 확인
                    if (mission.mission_reward == true)
                    {
                        return(new GetRewardMissionBaseReply()
                        {
                            Code = ErrorCode.AlreadyReward
                        });
                    }

                    // 보상 조건을 달성 했는지 확인
                    if (mission.CheckConditionReward() == false)
                    {
                        return(new GetRewardMissionBaseReply()
                        {
                            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, mission_base_data.reward_item_id, 1, new LogReason("A_MISSION", mission_base_data.id.ToString()), itemList);

                            AccountGoods.Set(user);
                        }

                    // 보상 받았음 기록
                    mission.mission_reward = true;
                    mission.IsDirty        = true;
                }
            }
            return(new GetRewardMissionBaseReply()
            {
                Code = ErrorCode.Success, Item = itemList, AccountGoods = AccountGoods
            });
        }
Exemple #9
0
        public static async Task <(ErrorCode, ItemList, Goods)> BuyItem(Session session, int shopItemId, int shopId)
        {
            var Item         = new ItemList();
            var AccountGoods = new Goods();

            // 상점 아이템 목록 체크
            var shop_item_data = ACDC.ShopItemListData[shopItemId];

            if (shop_item_data == null || shop_item_data == default(JShopItemListData))
            {
                return(ErrorCode.WrongParam, Item, AccountGoods);
            }

            var item_data = ACDC.GameItemData[shop_item_data.ItemId];

            if (item_data == null || item_data == default(JGameItemData))
            {
                return(ErrorCode.WrongParam, Item, AccountGoods);
            }

            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
            {
                // 유저 상점 리스트 얻기
                var shops = await ShopCache.Instance.GetEntities(session.member_no, session.user_no, true);

                // 상점 목록 갱신
                await Refresh(session, shops, true);

                // 구매하려는 아이템 목록에 있는지 체크
                var shop_item = shops.Where(x => x.shop_id == shopId && x.shop_item_id == shopItemId).FirstOrDefault();
                if (shop_item == null || shop_item == default(Models.Shop))
                {
                    return(ErrorCode.NotExist, Item, AccountGoods);
                }

                // 구매 한정 체크
                if (shop_item.purchase_count >= shop_item_data.PurchaseLimitedCount)
                {
                    return(ErrorCode.OverLimit, Item, AccountGoods);
                }

                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))
                    {
                        // 지불 금액 체크 및 소모
                        if (shop_item_data.PriceType != 0 && shop_item_data.PriceType != (int)GameItemId.Cash) // 0은 무료
                        {
                            var reason     = "S_BUY_ITEM";
                            var sub_reason = "";
                            if (item_data.Item_Type == (int)GameItemType.CharacterPiece)
                            {
                                reason     = "S_BUY_SMASHER";
                                sub_reason = item_data.LinkId.ToString();
                            }
                            if (shop_item_data.ShopItemType == (int)ShopItemType.Goods)
                            {
                                reason     = "S_BUY_MONEY";
                                sub_reason = item_data.LinkId.ToString();
                            }

                            if (Inventory.UseGoods(session, user, shop_item_data.PriceType, shop_item_data.PriceValue * shop_item.quantity, new LogReason(reason, sub_reason)) == false)
                            {
                                return(ErrorCode.NotEnough, Item, AccountGoods);
                            }
                        }

                        // 아이템 지급
                        shop_item.purchase_count += 1;
                        await ShopCache.Instance.UpdateEntity(session.member_no, shop_item);

                        await Inventory.Insert(session, user, character, shop_item_data.ItemId, shop_item.quantity, new LogReason(shop_item_data.logName, shop_item_data.LinkId.ToString()), Item);

                        AccountGoods.Set(user);

                        if (shop_item_data.logName == "AD")
                        {
                            _ = LogProxy.writeActionLog(session, "광고시청", "광고", shop_item_data.LinkId.ToString()).ConfigureAwait(false);
                        }
                    }
            }

            return(ErrorCode.Success, Item, AccountGoods);
        }
        public static void Test()
        {
            TestMail().Wait();

            TestString();

            var r111 = TestRanking().Result;

            return;

            {
                var values = new StackExchange.Redis.SortedSetEntry[]
                {
                    new StackExchange.Redis.SortedSetEntry("a:1", 0),
                    new StackExchange.Redis.SortedSetEntry("b:2", 0),
                    new StackExchange.Redis.SortedSetEntry("c:3", 0),
                    new StackExchange.Redis.SortedSetEntry("d:4", 0),
                    new StackExchange.Redis.SortedSetEntry("e:5", 0),
                    new StackExchange.Redis.SortedSetEntry("f:6", 0),
                    new StackExchange.Redis.SortedSetEntry("g:7", 0),
                };

                Cache.Instance.GetDatabase().SortedSetAdd("myzset", values);

                var redis_ret = Cache.Instance.GetDatabase().SortedSetRangeByValue("myzset", "c:", "+", StackExchange.Redis.Exclude.Start, 0, 1, StackExchange.Redis.CommandFlags.None);
                //var redis_ret = Cache.Instance.GetDatabase().SortedSetRangeByValue("myzset", "c:", "c:");
            }



            {
                var r21 = PlayerLog.GetPlayerInfo("990252821976346", 6029, 6029).Result;

                var r22 = WebAPIClient.Web.writeLog("990252821976346", "/log/writeActionLog", JsonConvert.SerializeObject(new ActionLog(r21)
                {
                    category = "캐릭터", action = "획득", label = "1"
                }));
            }

            {
                var ret_a = core.MathHelpers.GetResetTime("00:00:00", new DateTime(2020, 11, 13, 9, 10, 3));
                var ret_b = core.MathHelpers.GetResetTime("00:00:00", new DateTime(2020, 11, 14, 0, 0, 0));

                if (ret_a != ret_b)
                {
                }
            }


            var first  = new DateTime(2020, 9, 6);
            var second = new DateTime(2020, 9, 7);

            var dif2 = core.MathHelpers.weekDiff(first, second);

            first  = new DateTime(2020, 9, 8);
            second = new DateTime(2020, 9, 7);
            dif2   = core.MathHelpers.weekDiff(first, second);

            using (var context = new Lobby.Models.GameContext(0))
            {
                try
                {
                    var rows = context.shop.ToList();

                    foreach (var row in rows)
                    {
                        row.Clear();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }


            Task.Run(async() =>
            {
                await using (var user = await UserCache.GetUser(0, 4888, true, true))
                {
                    user.medal_charge_time = DateTime.UtcNow;
                    user.IsDirty           = true;
                    //UserQuery.UpdateUserMedalCharge(user).Wait();
                }
            });



            return;

            var list = BannedWordQuery.GetBannedWord().Result;


            //bool isLetter = false;
            if (Char.IsLetterOrDigit("test한글", 0))
            {
                //isLetter = true;
            }


            string letter = "test한글&\n";
            var    sret   = letter.IsLetterOrDigit();

            letter = "test한글111";
            sret   = letter.IsLetterOrDigit();


            //var r33 = UserQuery.UpdateUser(2672, "test15").Result;

            Task.Run(async() =>
            {
                //await LobbyService.LoadUserInfo(2672);
                //await LobbyService.LoadUserInfo(2672);

                var characters = await CharacterCache.Instance.GetEntities(0, 2672, true);

                await CharacterCache.Instance.RemoveEntity(0, characters[0]);

                await CharacterCache.Instance.RemoveEntities(0, 2672);

                characters = await CharacterCache.Instance.GetEntities(0, 2672, false);
            });

            Task.Run(async() =>
            {
                await using (var mylock = await RedLock.CreateLockAsync("lock:character:1"))
                {
                    var ret = mylock.IsAcquired;
                }
            });

            Task.Run(async() =>
            {
                await using (var mylock = await RedLock.CreateLockAsync("lock:character:1"))
                {
                    var ret = mylock.IsAcquired;
                }
            });

            var r  = WebAPIClient.Web.validate("990252821976346", "fwPla7fQ8ty9+DZT/lD//opW3OMPm7j2xvs2KuD+uYr9sjDBcwhG6af5snAmhRvRlplBuo/unVh4Ugt9HD7BWi2WfhT1va61xImzER4+UZzS7WO986OqafxFUTWyLV/k5UWPbS3ijhByFvqFR9j1kYk15clNysZGWi92KZTFr2BzzZ3rCKzcT6oVZjBFc3TqObRQBTI/40qwze1NQA7qReTr6OzO45hUebMuluFiHac=").Result;
            var r2 = WebAPIClient.Web.getInfo("990252821976346").Result;
            var r3 = WebAPIClient.Web.request("990252821976346", "/player/memberKey/get").Result;

            TestHttpClient().ConfigureAwait(false);


            //var charac = CharacterCache.InsertCharacter(new Models.Character() { user_no = 4 }).Result;


            var ret  = CharacterCache.Instance.GetEntities(0, 2019, true).Result;
            var ret2 = CharacterCache.Instance.GetEntities(0, 2019, true).Result;

            //WebAPIClient.Web.test();
            TestRankSeq();

            Lobby.Models.CommonContext.test();
            Lobby.Models.GameContext.test();
            Lobby.Models.LogContext.test();


            Task.Run(async() => await TestCache());
        }
Exemple #11
0
        public static async Task <(bool, ItemList, Goods)> GetMailItems(Session session, List <string> items, int characterId)
        {
            ItemList reply_items     = new ItemList();
            Goods    reply_goods     = new Goods();
            int      changed_item_id = 0;

            if (items == null || items.Count == 0)
            {
                items = new List <string>();

                string characterPieceReward   = ((int)GameItemId.CharacterPieceReward).ToString();
                getList.response.msg last_msg = null;
                long?nextPageKey = null;
                do
                {
                    var str = await GetMails(session.member_no, session.user_no, 100, nextPageKey);

                    if (str == string.Empty)
                    {
                        break;
                    }

                    last_msg = JsonConvert.DeserializeObject <getList.response.msg>(str);
                    if (last_msg == null)
                    {
                        break;
                    }

                    foreach (var mail in last_msg.messages)
                    {
                        // 우편에 아이템이 없는 경우 스킵 (시스템우편)
                        if (mail.items.Length == 0)
                        {
                            continue;
                        }

                        // 캐릭터 조각 선택 아이템 스킵
                        if (mail.items[0].itemId == characterPieceReward)
                        {
                            continue;
                        }

                        items.Add(mail.message.messageId);
                    }

                    nextPageKey = last_msg.nextPageKey;
                } while (last_msg.nextPageKey != -1);
            }
            else if (items.Count == 1 && characterId != 0)
            {
                var game_item_data = ACDC.GameItemData.Values.Where(x => x.Item_Type == (int)GameItemType.CharacterPiece && x.LinkId == characterId).FirstOrDefault();
                if (game_item_data == null || game_item_data == default)
                {
                    Log.Error($"GetMailItems {session.player_id} cannot find character : {characterId}");
                    return(false, reply_items, reply_goods);
                }


                var characters = await CharacterCache.Instance.GetEntities(session.member_no, session.user_no, true);

                if (characters.IsAvailable(game_item_data.id) == false)
                {
                    Log.Error($"GetMailItems {session.player_id} cannot receive character piece  : {characterId}");
                    return(false, reply_items, reply_goods);
                }

                changed_item_id = game_item_data.id;
            }

            if (items.Count == 0)
            {
                Log.Error($"GetMailItems {session.player_id} empty messages");
                return(false, reply_items, reply_goods);
            }

            var msg = new claimItems.request.msg();

            msg.messageIds = items.ToArray();

            string response = await WebAPIClient.Web.request(session.player_id, "/message/claimItems", JsonConvert.SerializeObject(msg));

            if (response == string.Empty)
            {
                Log.Error($"GetMailItems {session.player_id} empty claimItems");
                return(false, reply_items, reply_goods);
            }

            var mail_results = new Dictionary <int, int>();
            var success_msgs = new List <string>();
            var responseMsg  = JsonConvert.DeserializeObject <claimItems.response.msg>(response);

            foreach (var result in responseMsg.results)
            {
                //  정상 메시지 체크
                if (result.status != 200)
                {
                    continue;
                }

                foreach (var item in result.items)
                {
                    var item_id = int.Parse(item.itemCode);
                    // 받을 아이템이 캐릭터 조각 보상이면 캐릭터 조각으로 변경
                    if (item_id == (int)GameItemId.CharacterPieceReward)
                    {
                        item_id = changed_item_id;
                    }

                    mail_results.Increment(item_id, (int)item.quantity);
                }

                success_msgs.Add(result.messageId);
            }

            await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{session.session_id}"))
            {
                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))
                    {
                        foreach (var mail_result in mail_results)
                        {
                            await Inventory.Insert(session, user, character, mail_result.Key, mail_result.Value, new LogReason("A_MAIL"), reply_items);
                        }

                        reply_goods?.Set(user);
                    }
            }


            // 정상적으로 처리된 메시지만 finish 처리한다.
            msg.messageIds = success_msgs.ToArray();
            response       = await WebAPIClient.Web.request(session.player_id, "/message/finish", JsonConvert.SerializeObject(msg));

            if (response == string.Empty)
            {
                Log.Error($"GetMailItems {session.player_id} finish");
            }


            return(true, reply_items, reply_goods);
        }
Exemple #12
0
        /// <summary>
        /// 게임 결과 기다림
        /// </summary>
        /// <param name="session"></param>
        /// <param name="request"></param>
        /// <param name="responseStream"></param>
        /// <returns></returns>
        public static async Task WaitGameResult(Session session, string channel_id, JMapData map_data, JGameModeData game_mode)
        {
            string key = $"game_result:{channel_id}";

            Log.Information($"WaitGameResult {key}");

            Interlocked.Increment(ref RankMatchmaking.MatchCount);

            var queue = Cache.Instance.GetSubscriber().Subscribe(key);

            var cts = new CancellationTokenSource();

            cts.CancelAfter((int)game_result_expire.TotalMilliseconds);
            try
            {
                var ret = await queue.ReadAsync(cts.Token);

                Interlocked.Decrement(ref RankMatchmaking.MatchCount);

                ServerCommon.GameResult reply = JsonConvert.DeserializeObject <ServerCommon.GameResult>(ret.Message);

                Log.Information($"game result {ret.Message.ToString()}");

                int total_win_medal    = 0;
                int total_lose_medal   = 0;
                int total_draw_medal   = 0;
                int total_mvp_medal    = 0;
                int total_rankup_medal = 0;
                await Match.RemoveMatch(reply.match_id);

                var characterNames  = new List <string>();
                var characterLevels = new List <int>();


                foreach (var player in reply.player_result)
                {
                    if (player.Value.IsLeave)
                    {
                        continue;
                    }

                    var last_session = await Session.GetSession(player.Key, false);

                    if (last_session != null)
                    {
                        bool is_changed_character_rank_level = false;
                        await using (var mylock = await RedLock.CreateLockAsync($"lock:session:{last_session.session_id}"))
                        {
                            await using (var user = await UserCache.GetUser(last_session.member_no, last_session.user_no, true, true, true))
                                await using (var character = await CharacterCache.Instance.GetEntity(last_session.member_no, last_session.character_no, true, true, true))
                                {
                                    user.play_point += player.Value.play_point;
                                    var last_account_battle_score = user.battle_score;
                                    UserGrowth.IncreaseBattleScore(user, player.Value.battle_point);
                                    var last_battle_score = character.battle_score;
                                    var last_rank_level   = character.rank_level;
                                    CharacterGrowth.IncreaseBattleScore(character, player.Value.battle_point);

                                    var(abs, cbs, wc) = await Ranking.Update(last_session, reply.season_no, player.Value.battle_point, player.Value.IsWin);

                                    bool is_character_rank_level_up = false;
                                    if (last_rank_level != character.rank_level)
                                    {
                                        if (last_rank_level < character.rank_level)
                                        {
                                            is_character_rank_level_up = true;
                                        }
                                    }

                                    if (last_battle_score != character.battle_score)
                                    {
                                        var rankData = ACDC.RankData.GetRank(character.battle_score);
                                        if (rankData != null)
                                        {
                                            if (last_session.rank != rankData.Rank)
                                            {
                                                is_changed_character_rank_level = true;
                                                last_session.rank = rankData.Rank;
                                            }
                                        }
                                    }

                                    var last_medal  = user.medal;
                                    var medal_count = Medal.CalcMedal(user, last_session, reply.is_draw, player.Value, is_character_rank_level_up, game_mode, ref total_win_medal, ref total_lose_medal, ref total_draw_medal, ref total_mvp_medal, ref total_rankup_medal);
                                    await Inventory.Insert(last_session, user, character, (int)GameItemId.Medal, medal_count, null);


                                    // 배틀에서 넘어온 미션 데이터가 없는 경우 초기화
                                    if (player.Value.missions == null)
                                    {
                                        player.Value.missions = new Dictionary <int, int>();
                                    }
                                    player.Value.missions.Increment((int)MissionType.Mission_GetMedal, medal_count);

                                    await MissionManager.Progress(last_session, player.Value.missions);

                                    History.Info(last_session.member_no, last_session.user_no, last_session.character_no, HistoryLogAction.GainAccountBattleScore, (byte)HistoryLogReason.GameResultReward, (int)user.battle_score, (int)last_account_battle_score, reply.match_id.ToString(), "");
                                    History.Info(last_session.member_no, last_session.user_no, last_session.character_no, HistoryLogAction.GainCharacterBattleScore, (byte)HistoryLogReason.GameResultReward, (int)character.battle_score, (int)last_battle_score, reply.match_id.ToString(), "");

                                    characterNames.Add(last_session.user_name);
                                    characterLevels.Add(character.rank_level);
                                }
                        }

                        //Log.Information($"session:{last_session.session_id}, rank:{last_session.rank}");
                        if (is_changed_character_rank_level)
                        {
                            await Session.UpdateSessionLock(last_session.session_id, delegate(Session s) { s.rank = last_session.rank; });
                        }


                        // 게임 종료 이후 매칭 정보 삭제
                        await MatchUser.RemoveMatchUser(last_session.user_no);
                    }
                    else
                    {
                        Log.Warning($"game result lost session:{player.Key}, msg:{ret.Message}");
                    }
                }

                MatchLog.Info(reply, total_win_medal, total_lose_medal, total_draw_medal, total_mvp_medal, total_rankup_medal);

                string resultTp;
                if (reply.is_draw)
                {
                    resultTp = "26";
                    _        = LogProxy.writeActionLog(session, "플레이", "무승부", map_data.ID.ToString()).ConfigureAwait(false);
                }
                else if (reply.statistics.clear == 1)
                {
                    resultTp = "21";
                    _        = LogProxy.writeActionLog(session, "플레이", "클리어", map_data.ID.ToString()).ConfigureAwait(false);
                }
                else
                {
                    resultTp = "22";
                }

                _ = LogProxy.writeRoundLog(session, game_mode.Name, "", "", resultTp, 0, reply.statistics.start_time, reply.statistics.end_time, characterNames, characterLevels, "").ConfigureAwait(false);


                if (reply.statistics.leave_player > 0)
                {
                    _ = LogProxy.writeActionLog(session, "플레이", "이탈", map_data.ID.ToString(), reply.statistics.leave_player.ToString()).ConfigureAwait(false);
                }

                if (reply.statistics.normal_item > 0)
                {
                    _ = LogProxy.writeActionLog(session, "플레이", "일반아이템획득", map_data.ID.ToString(), reply.statistics.normal_item.ToString()).ConfigureAwait(false);
                }

                if (reply.statistics.tactic_item > 0)
                {
                    _ = LogProxy.writeActionLog(session, "플레이", "전략아이템획득", map_data.ID.ToString(), reply.statistics.tactic_item.ToString()).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException ex)
            {
                Log.Information($"game result timeout {ex.ToString()}");
            }
        }
Exemple #13
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
                });
            }
        }
Exemple #14
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
                });
            }
        }