public static async void SaveRoadAllInfo(MapUnit mapUnit, long teamId, bool saveRideRoadInfos = true, bool saveRideTotalInfos = true)
        {
            if (mapUnit == null)
            {
                Log.Error("SaveRoadAllInfo Failed, mapUnit == null");
                return;
            }

            if (mapUnit.MapUnitType == MapUnitType.Npc)
            {
                return;
            }

            var roadInfo      = mapUnit.CreateRideRecord(teamId);
            var roadTotalInfo = mapUnit.CreateRideTotalInfo();
            var user          = await UserDataHelper.FindOneUser(mapUnit.Uid);

            BsonDocument log = null;

            if (saveRideRoadInfos)
            {
                SaveRideRoadInfos(roadInfo);
            }
            if (saveRideTotalInfos)
            {
                SaveRideTotalInfo(user, roadTotalInfo, out log);
            }
            SaveUserAndBroadcastTarget(mapUnit, user, log);
        }
Esempio n. 2
0
        public async void Initial()
        {
            await UserDataHelper.AddDependView(new UserDataHelper.UserInfoView()
            {
                GoldText     = GoldTxtLab,
                HeadImg      = HeadIcon,
                NickNameText = PlayerName,
                UserIdText   = IDLab,
                SexGo        = ReferenceCollector.Get <GameObject>("SexGroup")
            });

            if (UserDataHelper.UserInfo.IsTourist)
            {
                ShowOrHideUpgradeAndChangePwdBtn(true);
            }

            if (UserDataHelper.UserInfo.PhoneNumber != 0)
            {
                BindPhoneNumLab.text = UserDataHelper.UserInfo.PhoneNumber.ToString();
            }
            else
            {
                BindPhoneNumLab.text = DataCenterComponent.Instance.tipInfo.NoBindPhoneNumTip;
            }
        }
        protected async ETTask RunAsync(MapUnit mapUnit, C2M_GiveAisatsu message)
        {
            await ETTask.CompletedTask;

            try
            {
                M2C_GiveAisatsu m2C_GiveAisatsu = new M2C_GiveAisatsu();
                if (mapUnit.Id == message.MapUnitId)
                {
                    Log.Error("µ¹¦Û¤v«öÆg¬O¤£¦æªº!");
                    return;
                }
                MapUnit target = mapUnit.Room.GetMapUnitById(message.MapUnitId);
                User    user   = await UserDataHelper.FindOneUser(mapUnit.Uid);

                m2C_GiveAisatsu.Name    = user?.name;
                m2C_GiveAisatsu.Content = message.Content;
                MapMessageHelper.BroadcastTarget(m2C_GiveAisatsu, new List <MapUnit> {
                    target
                });
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
        /// <summary>
        /// 查詢使用者的所有關係,包含User的基礎資料
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static async ETTask <List <RelationshipSimpleInfo> > GetUserRelationshipSimpleInfoList(long uid)
        {
            var relations = await GetUserRelationshipList(uid);

            var relationDict = relations.ToDictionary(e => e.targetUid, e => e);
            var users        = await UserDataHelper.FindUsers(relations.Select(e => e.targetUid).ToArray());

            return(users.Select(user =>
            {
                Relationship rel = null;
                RelationshipSimpleInfo info = new RelationshipSimpleInfo();
                info.Name = user.name;
                info.Location = user.location;
                info.Mileage = user.playerRideTotalInfo.Mileage;
                info.Uid = user.Id;
                info.DisconnectTime = 0;
                if (relationDict.TryGetValue(user.Id, out rel))
                {
                    info.RelationshipType = rel.relationshipType;
                }
                else
                {
                    info.RelationshipType = (int)Relationship.RelationType.Stranger;
                }
                return info;
            }).ToList());
        }
        /// <summary>
        /// 建立關係申請
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="targetUid"></param>
        /// <returns></returns>
        public static async ETTask <RelationshipApply> AddRelationshipApply(long senderUid, long receiverUid)
        {
            bool exist = await ExistRelationshipApply(senderUid, receiverUid);

            if (exist)
            {
                return(null);
            }

            var relationshipApply = ComponentFactory.CreateWithId <RelationshipApply>(IdGenerater.GenerateId());

            relationshipApply.applyId = relationshipApply.Id;

            var senderUser = await UserDataHelper.FindOneUser(senderUid);

            relationshipApply.senderUid      = senderUid;
            relationshipApply.senderName     = senderUser.name;
            relationshipApply.senderLocation = senderUser.location;
            relationshipApply.senderMileage  = senderUser.playerRideTotalInfo.Mileage;

            var receiverUser = await UserDataHelper.FindOneUser(receiverUid);

            relationshipApply.receiverUid      = receiverUid;
            relationshipApply.receiverName     = receiverUser.name;
            relationshipApply.receiverLocation = receiverUser.location;
            relationshipApply.receiverMileage  = receiverUser.playerRideTotalInfo.Mileage;

            await dbProxy.Save(relationshipApply);

            await dbProxy.SaveLog(senderUid, DBLog.LogType.RelationshipApply, relationshipApply);

            return(relationshipApply);
        }
Esempio n. 6
0
        protected async ETTask RunAsync(MapUnit mapUnit, C2M_GiveEmoticon message)
        {
            await ETTask.CompletedTask;

            try
            {
                M2C_GiveEmoticon m2C_GiveEmoticon = new M2C_GiveEmoticon();
                if (mapUnit.Id == message.MapUnitId)
                {
                    Log.Error("給自己按讚是不行的!");
                    return;
                }
                MapUnit target = mapUnit.Room.GetMapUnitById(message.MapUnitId);
                User    user   = await UserDataHelper.FindOneUser(mapUnit.Uid);

                m2C_GiveEmoticon.Name          = user?.name;
                m2C_GiveEmoticon.EmoticonIndex = message.EmoticonIndex;
                MapMessageHelper.BroadcastTarget(m2C_GiveEmoticon, new List <MapUnit> {
                    target
                });
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
Esempio n. 7
0
        protected async ETTask RunAsync(Session session, C2G_TeamInviteRefuse message, Action <G2C_TeamInviteRefuse> reply)
        {
            G2C_TeamInviteRefuse response = new G2C_TeamInviteRefuse();

            try
            {
                //取得自身資料
                Player player = session.GetComponent <SessionPlayerComponent>().Player;
                User   user   = await UserDataHelper.FindOneUser((player?.uid).GetValueOrDefault());

                if (user == null)
                {
                    response.Error = ErrorCode.ERR_AccountDoesntExist;
                    reply(response);
                    return;
                }

                //判斷邀請是否合法
                var inviteComponent = Game.Scene.GetComponent <InviteComponent>();
                var invite          = inviteComponent.GetByInviteId(message.InviteId);

                if (invite == null)
                {
                    response.Error = ErrorCode.ERR_InviteIdNotFind;
                    reply(response);
                    return;
                }

                if (invite.data.ReceiverUid != player?.uid)
                {
                    response.Error = ErrorCode.ERR_InviteNotSelf;
                    reply(response);
                    return;
                }

                //告知對方拒絕邀請
                var    proxy        = Game.Scene.GetComponent <CacheProxyComponent>();
                var    playerSync   = proxy.GetMemorySyncSolver <Player>();
                Player senderTarget = playerSync.Get <Player>(invite.data.SenderUid);
                if (senderTarget != null)
                {
                    G2C_TeamInviteTargerRefuse g2c_TeamInviteTargerRefuse = new G2C_TeamInviteTargerRefuse();
                    g2c_TeamInviteTargerRefuse.RefuseUid = player.uid;
                    GateMessageHelper.BroadcastTarget(g2c_TeamInviteTargerRefuse, invite.data.SenderUid);
                }

                //刪除該邀請
                await inviteComponent.DestroyByInviteId(message.InviteId);

                //回傳資料
                response.Error = ErrorCode.ERR_Success;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
        private async ETTask RunAsync(Player player, C2L_AddRelationship message, Action <L2C_AddRelationship> reply)
        {
            L2C_AddRelationship response = new L2C_AddRelationship();

            try
            {
                long uid = player.uid;
                //Apply
                var relationshipApply = await RelationshipDataHelper.AddRelationshipApply(uid, message.Uid);

                if (relationshipApply == null)
                {
                    response.Error = ErrorCode.ERR_RelationshipApplyInfo_AddFailed;
                    reply(response);
                    return;
                }
                response.Error = ErrorCode.ERR_Success;
                reply(response);

                // 確認玩家是在線,在線的話傳送好友資訊
                var relationshipApplyInfo = RelationshipApply.ConvertToRelationshipApplyInfo(relationshipApply);
                var uidUser = await UserDataHelper.FindOneUser(uid);

                var receiverUidUser = await UserDataHelper.FindOneUser(message.Uid);

                var    proxy      = Game.Scene.GetComponent <CacheProxyComponent>();
                var    playerSync = proxy.GetMemorySyncSolver <Player>();
                Player target     = playerSync.Get <Player>(message.Uid);
                if (target != null)
                {
                    var notifyRelationshipState_SenderNotRequested = new L2C_NotifyRelationshipApplyState()
                    {
                        AddApplyInfo = relationshipApplyInfo,
                        IsRequested  = false,
                    };
                    GateMessageHelper.BroadcastTarget(notifyRelationshipState_SenderNotRequested, message.Uid);
                }

                //傳給自己更新Apply列表
                var notifyRelationshipState_SenderIsRequested = new L2C_NotifyRelationshipApplyState()
                {
                    AddApplyInfo = relationshipApplyInfo,
                    IsRequested  = true,
                };
                GateMessageHelper.BroadcastTarget(notifyRelationshipState_SenderIsRequested, uid);

                // 推播告知receiverUser
                var firebase = Game.Scene.GetComponent <FirebaseComponent>();
                var lang     = Game.Scene.GetComponent <LanguageComponent>();
                // 7 = {0}向你發出好友邀請!
                var body = lang.GetString(receiverUidUser.language, 7);
                await firebase.SendOneNotification(receiverUidUser.firebaseDeviceToken, string.Empty, string.Format(body, uidUser.name));
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
        private async ETTask RunAsync(Player player, C2L_UpdateUserEquip message, Action <L2C_UpdateUserEquip> reply)
        {
            L2C_UpdateUserEquip response = new L2C_UpdateUserEquip();

            try
            {
                long uid = player.uid;
                if (uid <= 0)
                {
                    //未被Gate授權的帳戶
                    response.Error = ErrorCode.ERR_ConnectGateKeyError;
                }
                else
                {
                    User user = await UserDataHelper.FindOneUser(uid);

                    if (user == null)
                    {
                        response.Error = ErrorCode.ERR_AccountDoesntExist;
                    }
                    else
                    {
                        // 蒐集Log資訊(可一致性,但複雜)
                        var log = new BsonDocument();
                        if (user.playerCharSetting.CharacterId != message.CharSetting.CharacterId)
                        {
                            log["characterId"] = message.CharSetting.CharacterId;
                        }
                        if (user.playerCharSetting.BicycleId != message.CharSetting.BicycleId)
                        {
                            log["bicycleId"] = message.CharSetting.BicycleId;
                        }
                        if (user.playerCharSetting.BodyId != message.CharSetting.BodyId)
                        {
                            log["bodyId"] = message.CharSetting.BodyId;
                        }
                        if (user.playerCharSetting.DecorationId != message.CharSetting.DecorationId)
                        {
                            log["decorationId"] = message.CharSetting.DecorationId;
                        }
                        if (user.playerCharSetting.MedalId != message.CharSetting.MedalId)
                        {
                            log["medalId"] = message.CharSetting.MedalId;
                        }
                        user.playerCharSetting = message.CharSetting;
                        await UserDataHelper.UpsertUser(user, DBLog.LogType.UpdateUserCharacterSetting, log);

                        response.Error = ErrorCode.ERR_Success;
                    }
                }
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
        private async static ETTask RealmToGate(Session session, User user, R2C_Authentication response, bool isRefreshToken)
        {
            // 隨機分配GateServer
            StartConfig config = Game.Scene.GetComponent <RealmGateAddressComponent>().GetAddress();

            // Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
            IPEndPoint innerAddress = config.GetComponent <InnerConfig>().IPEndPoint;
            Session    gateSession  = Game.Scene.GetComponent <NetInnerComponent>().Get(innerAddress);
            //Game.Scene.GetComponent<PingComponent>().RemoveSession(session.Id);

            // 向Gate請求一個Key,Client可以拿這個Key連接Gate
            G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey()
            {
                Uid = user.Id
            });

            string outerAddress = config.GetComponent <OuterConfig>().Address2;

            // 創造權杖
            if (isRefreshToken)
            {
                SignInCryptographyHelper.Token tok = new SignInCryptographyHelper.Token
                {
                    uid = user.Id,
                    lastCreateTokenAt = user.lastCreateTokenAt,
                    salt = user.salt,
                };

                string token = SignInCryptographyHelper.EncodeToken(tok);
                response.Token = token;
            }

            PlayerRideTotalInfo playerRideTotalInfo = await UserDataHelper.QueryUserRideAllRecord(user);

            response.Error   = ErrorCode.ERR_Success;
            response.Address = outerAddress;
            response.Key     = g2RGetLoginKey.Key;
            response.Data    = new PlayerBaseInfo
            {
                Uid      = user.Id,
                Name     = user.name,
                Sex      = user.gender,
                Location = user.location,
                Height   = user.height,
                Weight   = user.weight,
                Birthday = user.birthday,
                CreateAt = user.createAt,
                // 校時用
                LastOnlineAt = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
                CharSetting  = user.playerCharSetting,
                TotalInfo    = playerRideTotalInfo,
                Language     = user.language,
            };
            response.LinkTypes.Clear();
            response.LinkTypes.AddRange(await GetAllLinkType(user.Id));
        }
Esempio n. 11
0
        /// <summary>
        /// 确认切换头像
        /// </summary>
        private async void OnConfirmChangeHead()
        {
            ETModel.Game.Scene.GetComponent <SoundComponent>().PlayClip(DataCenterComponent.Instance.soundInfo.click);

            if (ChangeHeadIndex == UserDataHelper.UserInfo.HeadId)
            {
                ChangeHeadView.SetActive(false);
                NormalInfoView.SetActive(true);
                return;
            }

            if (_isRequest)
            {
                Game.PopupComponent.ShowTips(DataCenterComponent.Instance.tipInfo.NotRepeatModifyTip);
                return;
            }

            _isRequest = true;
            try
            {
                G2C_ChangerUserInfo_Res chagerHead = (G2C_ChangerUserInfo_Res)await SessionComponent.Instance.Session.
                                                     Call(new C2G_ChangerUserInfo_Req()
                {
                    UserId = GamePrefs.GetUserId(),
                    Type   = 0,
                    HeadId = ChangeHeadIndex
                });

                if (chagerHead.Error != 0)
                {
                    Debug.Log(chagerHead.Message);
                    //                    GameHelper.ShowMessageBox(chagerHead.Message);
                    Game.PopupComponent.ShowMessageBox(chagerHead.Message);
                    _isRequest = false;
                    return;
                }

                ChangeHeadView.SetActive(false);
                NormalInfoView.SetActive(true);
                _isRequest = false;
            }
            catch (Exception e)
            {
                Log.Debug("修改头像错误:" + e.Message);
                Game.PopupComponent.ShowMessageBox(DataCenterComponent.Instance.tipInfo.ModifyHeadIdFailTip);
                _isRequest = false;
            }

            //            GameHelper.ShowMessageBox("修改头像成功!");
            Game.PopupComponent.ShowMessageBox(DataCenterComponent.Instance.tipInfo.ModifyHeadIdSuccTip);

            // 刷新显示
            await UserDataHelper.GetUserInfo(true);
        }
        public async static ETTask <List <AuthenticationType> > GetAllLinkType(long uid)
        {
            List <AuthenticationType> linkTypes = new List <AuthenticationType>();
            var thirdPartyUsers = await UserDataHelper.FindAllThirdPartyUser(uid);

            for (int i = 0; i < thirdPartyUsers?.Count; i++)
            {
                linkTypes.Add(PartyToAuthenticationType(thirdPartyUsers[i].party));
            }
            return(linkTypes);
        }
        public async static ETTask LinkByFaceBook(Player player, LinkInfo info, L2C_Link response)
        {
            string fbToken      = info.Secret;
            bool   isValidToken = await FacebookHelper.ValidateFacebookToken(fbToken);

            if (!isValidToken)
            {
                response.Error = ErrorCode.ERR_LinkFailed;
                return;
            }
            ThirdPartyInfo fbInfo = await FacebookHelper.GetFacebookUserInfo(fbToken);

            if (fbInfo == null)
            {
                response.Error = ErrorCode.ERR_LinkFailed;
                return;
            }
            long           now            = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            ThirdPartyUser thirdPartyUser = await UserDataHelper.FindOneThirdPartyUser(fbInfo.id, UserDataHelper.tagFB);

            if (thirdPartyUser == null)
            {
                long uid  = player.uid;
                User user = await UserDataHelper.FindOneUser(uid);

                if (user == null)
                {
                    response.Error = ErrorCode.ERR_LinkFailed;
                    return;
                }

                //綁定第三方-FB
                thirdPartyUser          = ComponentFactory.CreateWithId <ThirdPartyUser>(IdGenerater.GenerateId());
                thirdPartyUser.uid      = user.Id;
                thirdPartyUser.party    = UserDataHelper.tagFB;
                thirdPartyUser.userId   = fbInfo.id;
                thirdPartyUser.gender   = fbInfo.gender;
                thirdPartyUser.location = fbInfo.location;
                thirdPartyUser.email    = fbInfo.email;
                thirdPartyUser.name     = fbInfo.name;
                thirdPartyUser.birthday = fbInfo.birthday;
                thirdPartyUser.createAt = now;
                await UserDataHelper.UpsertThirdPartyUser(thirdPartyUser);

                //取得新的第三方列表
                response.LinkTypes.Clear();
                response.LinkTypes.AddRange(await GetAllLinkType(user.Id));
            }
            else
            {
                response.Error = ErrorCode.ERR_LinkIsExist;
            }
        }
        private async ETTask RunAsync(Player player, C2L_TeamReservationCancel message, Action <L2C_TeamReservationCancel> reply)
        {
            L2C_TeamReservationCancel response = new L2C_TeamReservationCancel();

            try
            {
                User user = await UserDataHelper.FindOneUser((player?.uid).GetValueOrDefault());

                if (user == null)
                {
                    response.Error = ErrorCode.ERR_AccountDoesntExist;
                    reply(response);
                    return;
                }

                //判斷是否為發起人
                var reservationComponent = Game.Scene.GetComponent <ReservationComponent>();
                var reservation          = reservationComponent.GetByReservationId(message.ReservationId);
                if (reservation.allData.SenderUid != player.uid)
                {
                    response.Error = ErrorCode.ERR_ReservationIsNotLeader;
                    reply(response);
                    return;
                }

                if (reservation.room != null)
                {
                    if (reservation.room.State != RoomState.Ready && reservation.room.State != RoomState.Start)
                    {
                        response.Error = ErrorCode.ERR_ReservationRoomStateCanNotToRemove;
                        reply(response);
                        return;
                    }
                    else
                    {
                        var lobbyComponent = Game.Scene.GetComponent <LobbyComponent>();
                        // 告知失去房間訊息
                        await lobbyComponent.BroadcastTeamLose(reservation.room.Id);
                    }
                }

                //刪除預約實體(DB會一起刪除)
                await reservationComponent.DestroyReservation(message.ReservationId);

                //回傳資料
                response.Error = ErrorCode.ERR_Success;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
Esempio n. 15
0
        private async void CreateRoomAsync(Reservation self)
        {
            var roomInfo = new RoomInfo()
            {
                RoomId         = 0,
                Title          = self.allData.SenderName,
                RoadSettingId  = self.allData.RoadSettingId,
                MaxMemberCount = 8,
                NowMemberCount = 0,
            };

            var teamRoomData = new TeamRoomData()
            {
                LeaderUid        = -1,
                LeaderName       = self.allData.SenderName,
                StartUTCTimeTick = self.allData.StartUTCTimeTick,
                IsReservation    = true,
            };

            var reservationMembers = new RepeatedField <ReservationMemberData>();

            for (int i = 0; i < self.allData.MemberUid?.count; i++)
            {
                var  uid  = self.allData.MemberUid[i];
                User user = await UserDataHelper.FindOneUser(uid);

                if (user == null)
                {
                    Log.Error($"Reservation CreateRoomAsync Failed, Can't find user, uid:{uid}");
                    continue;
                }
                var reservationMemberData = new ReservationMemberData()
                {
                    MemberIndex = i,
                    Uid         = user.Id,
                    Name        = user.name,
                    Location    = user.location,
                };
                reservationMembers.Add(reservationMemberData);
            }

            var lobbyComponent = Game.Scene.GetComponent <LobbyComponent>();
            // 隨機一個Map給要預約的房間
            var startConfig = NetworkHelper.GetRandomMap();

            self.room = await lobbyComponent.CreateTeamRoom(startConfig.AppId, roomInfo, teamRoomData);

            var reservationComponent = Game.Scene.GetComponent <ReservationComponent>();
            await reservationComponent.UpdateReservation(self);

            await lobbyComponent.SetReservationMember(self.room.Id, reservationMembers);
        }
        public static long SaveRideTeamRecord(RepeatedField <BattleLeaderboardUnitInfo> data)
        {
            var record = ComponentFactory.CreateWithId <RideTeamRecord>(IdGenerater.GenerateId());

            record.members = data.Aggregate(new RepeatedField <MemberBrief>(), (list, item) =>
            {
                list.Add(item.ToMemberBrief());
                return(list);
            });
            record.createAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            UserDataHelper.UpsertRideTeamRecord(record).Coroutine();
            return(record.Id);
        }
        /// <summary>
        /// 用name做模糊查詢非好友的清單
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="queringUids"></param>
        /// <returns></returns>
        public static async ETTask <RepeatedField <RelationshipSimpleInfo> > QueryLikeName(long uid, string userName, int count = 100)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(new RepeatedField <RelationshipSimpleInfo>());
            }

            // 先查詢自己的關係
            var relations = await GetUserRelationshipList(uid);

            var excludes = relations.Select(e => e.targetUid).ToList();

            // 排除自己
            excludes.Add(uid);

            // 排除已申請的玩家
            var relationApplyInfSenders = await GetRelationshipApplyInfoBySenderUid(uid);

            for (int i = 0; i < relationApplyInfSenders.Count; i++)
            {
                excludes.Add(relationApplyInfSenders[i].ReceiverUid);
            }

            // 排除向自己申請的玩家
            var relationApplyInfoReceivers = await GetRelationshipApplyInfoByReceiverUid(uid);

            for (int i = 0; i < relationApplyInfoReceivers.Count; i++)
            {
                excludes.Add(relationApplyInfoReceivers[i].SenderUid);
            }

            // (?i)表示忽略大小寫
            List <User> users = await UserDataHelper.FindUsers(e =>
                                                               !excludes.Contains(e.Id) && Regex.IsMatch(e.name, $"(?i){userName}")
                                                               , 0, count);

            return(users.Aggregate(new RepeatedField <RelationshipSimpleInfo>(), (list, user) =>
            {
                RelationshipSimpleInfo info = new RelationshipSimpleInfo();
                info.Name = user.name;
                info.Location = user.location;
                info.Mileage = user.playerRideTotalInfo.Mileage;
                info.Uid = user.Id;
                info.DisconnectTime = 0;
                info.RelationshipType = (int)Relationship.RelationType.Stranger;
                list.Add(info);
                return list;
            }));
        }
Esempio n. 18
0
        /// <summary>
        /// 设置用户信息
        /// </summary>
        public async void SetAccountInfo()
        {
            await UserDataHelper.AddDependView(new UserDataHelper.UserInfoView()
            {
                HeadImg = _HeadImage,

                NickNameText = _PlayerNameText,

                GoldText = _GoldNumberText,

                UserIdText = _PlayerIdText
            }, true);

            lobby.GameLobbyGameTypeSelectPlugin.GameTypeGoldNumberText.text = UserDataHelper.UserInfo.Gold.ToString("F2");
        }
        protected async ETTask RunAsync(Session session, C2G_TeamInviteRefuseAll message, Action <G2C_TeamInviteRefuseAll> reply)
        {
            G2C_TeamInviteRefuseAll response = new G2C_TeamInviteRefuseAll();

            try
            {
                //取得自身資料
                Player player = session.GetComponent <SessionPlayerComponent>().Player;
                User   user   = await UserDataHelper.FindOneUser((player?.uid).GetValueOrDefault());

                if (user == null)
                {
                    response.Error = ErrorCode.ERR_AccountDoesntExist;
                    reply(response);
                    return;
                }

                var inviteComponent = Game.Scene.GetComponent <InviteComponent>();
                var inviteList      = inviteComponent.GetByUid(player.uid);
                var proxy           = Game.Scene.GetComponent <CacheProxyComponent>();
                var playerSync      = proxy.GetMemorySyncSolver <Player>();

                for (int i = 0; i < inviteList.Count; i++)
                {
                    //告知對方拒絕邀請
                    Player senderTarget = playerSync.Get <Player>(inviteList[i].data.SenderUid);
                    if (senderTarget != null)
                    {
                        G2C_TeamInviteTargerRefuse g2c_TeamInviteTargerRefuse = new G2C_TeamInviteTargerRefuse();
                        g2c_TeamInviteTargerRefuse.RefuseUid = player.uid;
                        GateMessageHelper.BroadcastTarget(g2c_TeamInviteTargerRefuse, inviteList[i].data.SenderUid);
                    }
                }

                //刪除自身全部邀請
                await inviteComponent.DestroyByUid(player.uid);

                //回傳資料
                response.Error = ErrorCode.ERR_Success;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
        public async static ETTask <int> AuthenticationByBot(string deviceUniqueIdentifier)
        {
            long           now            = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            ThirdPartyUser thirdPartyUser = await UserDataHelper.FindOneThirdPartyUser(deviceUniqueIdentifier, UserDataHelper.tagGuest);

            User user = null;

            if (thirdPartyUser == null)
            {
                user = ComponentFactory.CreateWithId <User>(IdGenerater.GenerateId());
                string salt         = CryptographyHelper.GenerateRandomId();
                string password     = CryptographyHelper.GenerateRandomId(16);
                string hashPassword = CryptographyHelper.MD5Encoding(password, salt);
                user.salt                          = salt;
                user.hashPassword                  = hashPassword;
                user.createAt                      = now;
                user.name                          = $"{user.Id}";
                user.playerCharSetting             = new PlayerCharSetting();
                user.playerCharSetting.CharacterId = 1L;
                user.playerRideTotalInfo           = new RideTotalInfo();
                user.language                      = 10;
                user.identity                      = (int)User.Identity.TestPlayer;
                user.userBagCapacity               = EquipmentDataHelper.GetDefaultUserBag();
                await UserDataHelper.SinUserUp(user);

                //註冊第三方-Guest
                thirdPartyUser          = ComponentFactory.CreateWithId <ThirdPartyUser>(IdGenerater.GenerateId());
                thirdPartyUser.uid      = user.Id;
                thirdPartyUser.party    = UserDataHelper.tagGuest;
                thirdPartyUser.userId   = deviceUniqueIdentifier;
                thirdPartyUser.name     = "";
                thirdPartyUser.gender   = "";
                thirdPartyUser.location = "";
                thirdPartyUser.email    = "";
                thirdPartyUser.birthday = "";
                thirdPartyUser.createAt = now;
                await UserDataHelper.UpsertThirdPartyUser(thirdPartyUser);

                return(ErrorCode.ERR_Success);
            }
            else
            {
                return(ErrorCode.ERR_DeviceUniqueIdentifierIsExist);
            }
        }
        /// <summary>
        /// 用uids查詢非好友的清單
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="queringUids"></param>
        /// <returns></returns>
        public static async ETTask <RepeatedField <RelationshipSimpleInfo> > QueryByUids(long uid, params long[] queringUids)
        {
            // 先查詢自己的關係
            var relations = await GetUserRelationshipList(uid);

            var excludes = relations.Select(e => e.targetUid).ToList();

            // 排除自己
            excludes.Add(uid);

            // 排除已申請的玩家
            var relationApplyInfSenders = await GetRelationshipApplyInfoBySenderUid(uid);

            for (int i = 0; i < relationApplyInfSenders.Count; i++)
            {
                excludes.Add(relationApplyInfSenders[i].ReceiverUid);
            }

            // 排除向自己申請的玩家
            var relationApplyInfoReceivers = await GetRelationshipApplyInfoByReceiverUid(uid);

            for (int i = 0; i < relationApplyInfoReceivers.Count; i++)
            {
                excludes.Add(relationApplyInfoReceivers[i].SenderUid);
            }

            // 用差集過濾下
            var finds = queringUids.Except(excludes);

            List <User> users = await UserDataHelper.FindUsers(finds.ToArray());

            return(users.Aggregate(new RepeatedField <RelationshipSimpleInfo>(), (list, user) =>
            {
                RelationshipSimpleInfo info = new RelationshipSimpleInfo();
                info.Name = user.name;
                info.Location = user.location;
                info.Mileage = user.playerRideTotalInfo.Mileage;
                info.Uid = user.Id;
                info.DisconnectTime = 0;
                info.RelationshipType = (int)Relationship.RelationType.Stranger;
                list.Add(info);
                return list;
            }));
        }
        /// <summary>
        /// 根據筆數跟偏移,尋找跟自己沒有關係的人們
        /// 回傳資料集合跟DB表的總長度
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="skip"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public static async ETTask <Tuple <List <RelationshipSimpleInfo>, long> > GetStrangers(long uid, long skip = 0L, long limit = getStrangerLimitCount)
        {
            var relations = await GetUserRelationshipList(uid);

            var excludes = relations.Select(e => e.targetUid).ToList();

            // 排除自己
            excludes.Add(uid);

            // 排除已申請的玩家
            var relationApplyInfSenders = await GetRelationshipApplyInfoBySenderUid(uid);

            for (int i = 0; i < relationApplyInfSenders.Count; i++)
            {
                excludes.Add(relationApplyInfSenders[i].ReceiverUid);
            }

            // 排除向自己申請的玩家
            var relationApplyInfoReceivers = await GetRelationshipApplyInfoByReceiverUid(uid);

            for (int i = 0; i < relationApplyInfoReceivers.Count; i++)
            {
                excludes.Add(relationApplyInfoReceivers[i].SenderUid);
            }

            List <User> users = await UserDataHelper.FindUsers(entity => !excludes.Contains(entity.Id), skip, limit);

            long totalCount = await dbProxy.QueryCount <User>(entity => !excludes.Contains(entity.Id));

            List <RelationshipSimpleInfo> list = users.Select(user =>
            {
                RelationshipSimpleInfo info = new RelationshipSimpleInfo();
                info.Name             = user.name;
                info.Location         = user.location;
                info.Mileage          = user.playerRideTotalInfo.Mileage;
                info.Uid              = user.Id;
                info.DisconnectTime   = 0;
                info.RelationshipType = (int)Relationship.RelationType.Stranger;
                return(info);
            }).ToList();

            return(new Tuple <List <RelationshipSimpleInfo>, long>(list, totalCount));
        }
Esempio n. 23
0
        public async override void Run(long messageId)
        {
            StartConfig startConfig = Game.Scene.GetComponent <StartConfigComponent>().StartConfig;

            if (!appTypes.Contains(startConfig.AppType))
            {
                Log.Warning($"not supported server type on event: {typeof(Event_MessageTip).Name}!");
                return;
            }

            var proxy      = Game.Scene.GetComponent <CacheProxyComponent>();
            var playerSync = proxy.GetMemorySyncSolver <Player>();

            var messageTipSetting = Game.Scene.GetComponent <ConfigComponent>().Get(typeof(MessageTipSetting), messageId) as MessageTipSetting;

            if (messageTipSetting != null)
            {
                foreach (var playerData in playerSync.Data)
                {
                    var uid  = playerData.Key;
                    var user = await UserDataHelper.FindOneUser(uid);

                    var tipContent = string.Empty;
                    switch (user.language)
                    {
                    //SystemLanguage.English
                    default:
                    case 10:
                        tipContent = messageTipSetting.en_context;
                        break;

                    //SystemLanguage.ChineseTraditional
                    case 41:
                        tipContent = messageTipSetting.zh_tw_context;
                        break;
                    }
                    GateMessageHelper.BroadcastTarget(new G2C_MessageTip()
                    {
                        TipContent = tipContent
                    }, uid);
                }
            }
        }
        public async static ETTask LinkByAppleId(Player player, LinkInfo info, L2C_Link response)
        {
            string         appleId   = CryptographyHelper.AESDecrypt(info.Secret);
            ThirdPartyInfo appleInfo = new ThirdPartyInfo
            {
                id = appleId,
            };
            long           now            = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            ThirdPartyUser thirdPartyUser = await UserDataHelper.FindOneThirdPartyUser(appleInfo.id, UserDataHelper.tagAppleId);

            if (thirdPartyUser == null)
            {
                long uid  = player.uid;
                User user = await UserDataHelper.FindOneUser(uid);

                if (user == null)
                {
                    response.Error = ErrorCode.ERR_LinkFailed;
                    return;
                }

                // 綁定第三方-Apple
                thirdPartyUser          = ComponentFactory.CreateWithId <ThirdPartyUser>(IdGenerater.GenerateId());
                thirdPartyUser.uid      = user.Id;
                thirdPartyUser.party    = UserDataHelper.tagAppleId;
                thirdPartyUser.userId   = appleInfo.id;
                thirdPartyUser.gender   = appleInfo.gender;
                thirdPartyUser.location = appleInfo.location;
                thirdPartyUser.email    = appleInfo.email;
                thirdPartyUser.name     = appleInfo.name;
                thirdPartyUser.birthday = appleInfo.birthday;
                thirdPartyUser.createAt = now;
                await UserDataHelper.UpsertThirdPartyUser(thirdPartyUser);

                // 取得新的第三方列表
                response.LinkTypes.Clear();
                response.LinkTypes.AddRange(await GetAllLinkType(user.Id));
            }
            else
            {
                response.Error = ErrorCode.ERR_LinkIsExist;
            }
        }
        private static async void SaveUserAndBroadcastTarget(MapUnit mapUnit, User user, BsonDocument log)
        {
            await UserDataHelper.UpsertUser(user, DBLog.LogType.UpdateUserRideTotalRecord, log);

            // 如果玩家在線上 告知該玩家異動紀錄
            var    proxy      = Game.Scene.GetComponent <CacheProxyComponent>();
            var    playerSync = proxy.GetMemorySyncSolver <Player>();
            Player selfPlayer = playerSync.Get <Player>(mapUnit.Uid);

            if (selfPlayer != null)
            {
                PlayerRideTotalInfo playerRideTotalInfo = await UserDataHelper.QueryUserRideAllRecord(user);

                G2C_UpdatePlayerRideTotalInfo g2c_UpdatePlayerRideInfo = new G2C_UpdatePlayerRideTotalInfo()
                {
                    TotalInfo = playerRideTotalInfo,
                };
                GateMessageHelper.BroadcastTarget(g2c_UpdatePlayerRideInfo, mapUnit.Uid);
            }
        }
        private async ETTask RunAsync(Player player, C2L_UpdateUserLanguage message, Action <L2C_UpdateUserLanguage> reply)
        {
            L2C_UpdateUserLanguage response = new L2C_UpdateUserLanguage();

            try
            {
                long uid = player.uid;
                if (uid <= 0)
                {
                    //未被Gate授權的帳戶
                    response.Error = ErrorCode.ERR_ConnectGateKeyError;
                }
                else
                {
                    User user = await UserDataHelper.FindOneUser(uid);

                    if (user == null)
                    {
                        response.Error = ErrorCode.ERR_AccountDoesntExist;
                    }
                    else
                    {
                        var log = new BsonDocument();
                        if (user.language != message.Language)
                        {
                            log["language"] = message.Language;
                            user.language   = message.Language;
                        }
                        await UserDataHelper.UpsertUser(user, DBLog.LogType.UpdateUserLanguage, log);

                        response.Error = ErrorCode.ERR_Success;
                    }
                }
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// 打开修改头像页面
        /// </summary>
        private async void OnChangeHead()
        {
            ETModel.Game.Scene.GetComponent <SoundComponent>().PlayClip(DataCenterComponent.Instance.soundInfo.click);
            NormalInfoView.SetActive(false);
            ChangeHeadView.SetActive(true);

            // 选择默认的头像
            var userInfo = await UserDataHelper.GetUserInfo();

            if (ChangeHeadIndex != 0 && ChangeHeadIndex == userInfo.HeadId)
            {
                return;
            }
            LastSelectHead?.SetActive(false);

            ChangeHeadIndex = userInfo.HeadId;
            LastSelectHead  = ChangeHeadObjs.GetChild(userInfo.HeadId - 0).GetChild(2).gameObject;
            LastSelectHead.SetActive(true);

            //修改
            changeHeadIcon.sprite = LastSelectHead.transform.parent.Find("icon").GetComponent <Image>().sprite;
        }
        private async ETVoid RunAsync(Session session, C2R_SignUp message, Action <R2C_SignUp> reply)
        {
            R2C_SignUp response = new R2C_SignUp();

            try
            {
                var plain = CryptographyHelper.AESDecrypt(message.Secret);
                var req   = BsonSerializer.Deserialize <C2R_SignUp>(plain);
                response.Error = await UserDataHelper.SignUp(req.Email, req.Password);

                if (response.Error != ErrorCode.ERR_Success)
                {
                    response.ErrorCodeList = new RepeatedField <int> {
                        ErrorCode.ERR_AccountSisnUpRepeatly
                    };
                }
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
        public async static ETTask AuthenticationByToken(Session session, AuthenticationInfo info, R2C_Authentication response)
        {
            SignInCryptographyHelper.Token tok = null;
            try
            {
                tok = SignInCryptographyHelper.DecodeToken(info.Secret);
                if (tok == null)
                {
                    response.Error = ErrorCode.ERR_InvalidToken;
                    return;
                }
            }
            catch (Exception e)
            {
                response.Error = ErrorCode.ERR_InvalidToken;
                return;
            }

            User user = await UserDataHelper.FindOneUser(tok.uid);

            if (user != null)
            {
                if (user.salt != tok.salt || user.lastCreateTokenAt != tok.lastCreateTokenAt)
                {
                    response.Error = ErrorCode.ERR_InvalidToken;
                }
                else
                {
                    await SignInByUid(session, user, response, info.FirebaseDeviceToken, false, UserDataHelper.tagToken);
                }
            }
            else
            {
                response.Error = ErrorCode.ERR_AccountDoesntExist;
            }
        }
        private async static ETTask SignInByUid(Session session, User user, R2C_Authentication response, string firebaseDeviceToken, bool isRefreshToken, string signInMethod)
        {
            BsonDocument log = new BsonDocument();

            // 更新user登入資訊
            user.lastOnlineAt   = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            log["lastOnlineAt"] = user.lastOnlineAt; // 最後登入時間
            log["signInMethod"] = signInMethod;      // 登入方式
            if (user.firebaseDeviceToken != firebaseDeviceToken)
            {
                user.firebaseDeviceToken   = firebaseDeviceToken;
                log["firebaseDeviceToken"] = user.firebaseDeviceToken; // 最後更新的FirebaseToken
            }
            if (isRefreshToken)
            {
                user.lastCreateTokenAt   = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                log["lastCreateTokenAt"] = user.lastCreateTokenAt; // 最後更新Token的時間
            }
            log["ip"] = session.RemoteAddress.ToString();          // 登入位址
            await UserDataHelper.UpsertUser(user, DBLog.LogType.SignUserIn, log);

            // 從Realm轉登到Gate並傳給Client用戶資料
            await RealmToGate(session, user, response, isRefreshToken);
        }