Exemplo n.º 1
0
        /// <summary>
        /// 打开会话
        /// </summary>
        /// <returns>The session.</returns>
        internal Task OpenSession(AVIMClient client)
        {
            var tcs         = new TaskCompletionSource <bool>();
            var sessionOpen = new SessionCommand {
                configBitmap = 1,
                Ua           = "net-universal/1.0.6999.29889",
                N            = null,
                T            = 0,
                S            = null,
            };
            var cmd = commandFactory.NewRequest(client.ClientId, CommandType.Session, OpType.Open);

            cmd.sessionMessage = sessionOpen;
            SendRequest(cmd).ContinueWith(t => {
                AVRealtime.Context.Post(() => {
                    if (t.IsFaulted)
                    {
                        AVRealtime.PrintLog("open session error");
                        tcs.SetException(t.Exception.InnerException);
                    }
                    else
                    {
                        var res           = t.Result;
                        var sessionOpened = res.sessionMessage;
                        // TODO 判断会话打开结果

                        idToClient.Add(client.ClientId, client);
                        tcs.SetResult(true);
                    }
                });
            });
            return(tcs.Task);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 查询对方 client Id 是否在线
        /// </summary>
        /// <param name="targetClientId">单个 client Id</param>
        /// <param name="targetClientIds">多个 client Id 集合</param>
        /// <returns></returns>
        public Task <IEnumerable <Tuple <string, bool> > > PingAsync(string targetClientId = null, IEnumerable <string> targetClientIds = null)
        {
            List <string> queryIds = null;

            if (targetClientIds != null)
            {
                queryIds = targetClientIds.ToList();
            }
            if (queryIds == null && string.IsNullOrEmpty(targetClientId))
            {
                throw new ArgumentNullException("必须查询至少一个 client id 的状态,targetClientId 和 targetClientIds 不可以同时为空");
            }
            queryIds.Add(targetClientId);

            var cmd = new SessionCommand()
                      .SessionPeerIds(queryIds)
                      .Option("query");

            return(this.RunCommandAsync(cmd).OnSuccess(t =>
            {
                var result = t.Result;
                List <Tuple <string, bool> > rtn = new List <Tuple <string, bool> >();
                var onlineSessionPeerIds = AVDecoder.Instance.DecodeList <string>(result.Item2["onlineSessionPeerIds"]);
                foreach (var peerId in targetClientIds)
                {
                    rtn.Add(new Tuple <string, bool>(peerId, onlineSessionPeerIds.Contains(peerId)));
                }
                return rtn.AsEnumerable();
            }));
        }
        /// <summary>
        /// 自动重连
        /// </summary>
        /// <returns></returns>
        public Task AutoReconnect()
        {
            return(OpenAsync(_wss).ContinueWith(t =>
            {
                state = Status.Reconnecting;
                var cmd = new SessionCommand()
                          .UA(VersionString)
                          .Tag(_tag)
                          .R(1)
                          .SessionToken(this._sesstionToken)
                          .Option("open")
                          .PeerId(_clientId);

                return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(_clientId)).OnSuccess(_ =>
                {
                    return AVIMCommandRunner.RunCommandAsync(cmd);
                }).Unwrap();
            }).Unwrap().OnSuccess(s =>
            {
                var result = s.Result;
                if (result.Item1 == 0)
                {
                    state = Status.Online;
                }
                else
                {
                    state = Status.Offline;
                }
            }));
        }
Exemplo n.º 4
0
        private void UpdateSession(SessionCommand session)
        {
            token = session.St;
            int ttl = session.StTtl;

            expiredAt = DateTimeOffset.Now + TimeSpan.FromSeconds(ttl);
        }
Exemplo n.º 5
0
        private void onLoginSuccess(SessionCommand sessionCommand, User user, ApiContext context)
        {
            _clients.Add(user.Id, sessionCommand.CurrentSession);
            Command command = new Command(CommandType.Login, WorldCommand.None, true, user.Clone());

            _networkController.Networker.Send(sessionCommand.CurrentSession, command.ToBytes());
        }
Exemplo n.º 6
0
        public static void Login(SessionCommand sessionCommand, string username, string password,
                                 OnLoginSuccessAction onLoginSuccess, OnLoginFailedAction onLoginFailed)
        {
            var formData = new Dictionary <string, string>();

            formData.Add("username", username);
            formData.Add("password", password);

            DoPostRequest(formData, "account&process=login",
                          (IWebRequest result) => {
                var apiResult = new ApiResult <ChunkDataJsonObject>(result.Json);
                if (apiResult.IsError)
                {
                    onLoginFailed(sessionCommand, apiResult);
                }
                else
                {
                    var user   = apiResult.CurrentUser;
                    _sessionId = apiResult.SessionId;
                    _user      = user;
                    onLoginSuccess(sessionCommand, _user, apiResult);
                }
            },
                          (WebContextException error) => {
                OnError(new ApiException(1, "Could not login.", error));
            });
        }
Exemplo n.º 7
0
        /// <summary>
        /// 创建与 LeanMessage 云端的长连接
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task ConnectAsync(CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new Exception("当前 ClientId 为空,无法登录服务器。");
            }
            state = Status.Connecting;
            return(RouterController.GetAsync(cancellationToken).OnSuccess(_ =>
            {
                return OpenAsync(_.Result.server);
            }).Unwrap().OnSuccess(t =>
            {
                var cmd = new SessionCommand()
                          .UA(platformHooks.ua + Version)
                          .Option("open")
                          .AppId(AVClient.ApplicationId)
                          .PeerId(clientId);

                return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(this.clientId)).OnSuccess(_ =>
                {
                    return AVIMClient.AVCommandRunner.RunCommandAsync(cmd);
                }).Unwrap();
            }).Unwrap().OnSuccess(s =>
            {
                state = Status.Online;
                var response = s.Result.Item2;
                websocketClient.OnMessage += WebsocketClient_OnMessage;
                websocketClient.OnClosed += WebsocketClient_OnClosed;
                websocketClient.OnError += WebsocketClient_OnError;
                RegisterNotices();
            }));
        }
Exemplo n.º 8
0
        /// <summary>
        /// 创建 Client
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="tag"></param>
        /// <param name="deviceId">设备唯一的 Id。如果是 iOS 设备,需要将 iOS 推送使用的 DeviceToken 作为 deviceId 传入</param>
        /// <param name="secure">是否强制加密 wss 链接</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <AVIMClient> CreateClientAsync(string clientId,
                                                   string tag      = null,
                                                   string deviceId = null,
                                                   bool secure     = true,
                                                   CancellationToken cancellationToken = default(CancellationToken))
        {
            lock (mutex)
            {
                var client = PreLogIn(clientId, tag, deviceId);

                AVRealtime.PrintLog("begin OpenAsync.");
                return(OpenAsync(secure, Subprotocol, true, cancellationToken).OnSuccess(t =>
                {
                    if (!t.Result)
                    {
                        return Task.FromResult <AVIMCommand>(null);
                    }
                    AVRealtime.PrintLog("websocket server connected, begin to open sesstion.");
                    SetNetworkState();
                    var cmd = new SessionCommand()
                              .UA(VersionString)
                              .Tag(tag)
                              .DeviceId(deviceId)
                              .Option("open")
                              .PeerId(clientId);

                    ToggleNotification(true);
                    return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId));
                }).Unwrap().OnSuccess(x =>
                {
                    var cmd = x.Result;
                    if (cmd == null)
                    {
                        return Task.FromResult <Tuple <int, IDictionary <string, object> > >(null);
                    }
                    return this.RunCommandAsync(cmd);
                }).Unwrap().OnSuccess(s =>
                {
                    if (s.Result == null)
                    {
                        return null;
                    }
                    AVRealtime.PrintLog("sesstion opened.");
                    state = Status.Online;
                    ToggleHeartBeating(true);
                    var response = s.Result.Item2;
                    if (response.ContainsKey("st"))
                    {
                        _sesstionToken = response["st"] as string;
                    }
                    if (response.ContainsKey("stTtl"))
                    {
                        var stTtl = long.Parse(response["stTtl"].ToString());
                        _sesstionTokenExpire = DateTime.Now.ToUnixTimeStamp() + stTtl * 1000;
                    }
                    AfterLogIn(client);
                    return client;
                }));
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 退出登录或者切换账号
        /// </summary>
        /// <returns></returns>
        public Task CloseAsync()
        {
            var cmd = new SessionCommand().Option("close");

            return(this.RunCommandAsync(cmd).ContinueWith(t =>
            {
                m_OnSessionClosed(this, null);
            }));
        }
Exemplo n.º 10
0
 public SessionAnswer(long sessionID, SessionCommand command, Answer reply)
 {
     SessionID = sessionID;
     if ((Command = command) == null)
     {
         throw new System.ArgumentNullException(nameof(command));
     }
     Reply = reply;
 }
Exemplo n.º 11
0
        /// <summary>
        /// 退出登录或者切换账号
        /// </summary>
        /// <returns></returns>
        public Task CloseAsync()
        {
            var cmd = new SessionCommand().Option("close");

            return(this.LinkedRealtime.AVIMCommandRunner.RunCommandAsync(cmd).ContinueWith(t =>
            {
                this.LinkedRealtime.LogOut();
            }));
        }
Exemplo n.º 12
0
        /// <summary>
        /// 创建 Client
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="tag"></param>
        /// <param name="deviceId">设备唯一的 Id。如果是 iOS 设备,需要将 iOS 推送使用的 DeviceToken 作为 deviceId 传入</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <AVIMClient> CreateClient(
            string clientId,
            string tag      = null,
            string deviceId = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            _clientId = clientId;
            _tag      = tag;
            if (_tag != null)
            {
                if (deviceId == null)
                {
                    throw new ArgumentNullException(deviceId, "当 tag 不为空时,必须传入当前设备不变的唯一 id(deviceId)");
                }
            }

            if (string.IsNullOrEmpty(clientId))
            {
                throw new Exception("当前 ClientId 为空,无法登录服务器。");
            }
            return(OpenAsync(cancellationToken).OnSuccess(t =>
            {
                ToggleNotification(true);

                var cmd = new SessionCommand()
                          .UA(VersionString)
                          .Tag(tag)
                          .Argument("deviceId", deviceId)
                          .Option("open")
                          .PeerId(clientId);

                return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId)).OnSuccess(_ =>
                {
                    return AVIMCommandRunner.RunCommandAsync(cmd);
                }).Unwrap();
            }).Unwrap().OnSuccess(s =>
            {
                if (s.Exception != null)
                {
                    var imException = s.Exception.InnerException as AVIMException;
                }
                state = Status.Online;
                var response = s.Result.Item2;
                if (response.ContainsKey("st"))
                {
                    _sesstionToken = response["st"] as string;
                }
                if (response.ContainsKey("stTtl"))
                {
                    var stTtl = long.Parse(response["stTtl"].ToString());
                    _sesstionTokenExpire = DateTime.Now.UnixTimeStampSeconds() + stTtl;
                }
                var client = new AVIMClient(clientId, tag, this);
                return client;
            }));
        }
Exemplo n.º 13
0
        private async Task Refresh()
        {
            SessionCommand session = await NewSessionCommand();

            GenericCommand request = NewCommand(CommandType.Session, OpType.Refresh);

            request.SessionMessage = session;
            GenericCommand response = await Connection.SendRequest(request);

            UpdateSession(response.SessionMessage);
        }
Exemplo n.º 14
0
        void ProcessSession(SessionCommand session)
        {
            var sb = new StringBuilder();

            ProcessHostIp(session);
            _playerId = session.PlayerId;
            if (session.Hosting)
            {
                sb.Append("(HOSTING)");
            }
            Message = sb.ToString();
        }
Exemplo n.º 15
0
        internal override void HandleNotification(GenericCommand notification)
        {
            switch (notification.Op)
            {
            case OpType.Closed: {
                Connection.UnRegister(Client);
                SessionCommand command = notification.SessionMessage;
                Client.OnClose(command.Code, command.Reason);
            }
            break;

            default:
                break;
            }
        }
Exemplo n.º 16
0
        void ProcessHostIp(SessionCommand session)
        {
            var currentHostIp = _hostIP == null ? null : _hostIP.ToString();

            if (session.HostIP == currentHostIp && session.Hosting == _hosting)
            {
                return;
            }

            _hosting = session.Hosting;
            var addr = session.HostIP;

            _hostIP = string.IsNullOrWhiteSpace(addr) ? null : new ServerAddress(addr);

            CalculatedGameSettings.RaiseEvent(new MyActiveServerAddressChanged(_hostIP));
        }
Exemplo n.º 17
0
        internal async Task Open(bool force)
        {
            await Connection.Connect();

            SessionCommand session = await NewSessionCommand();

            session.R            = !force;
            session.ConfigBitmap = 0xAB;
            GenericCommand request = NewCommand(CommandType.Session, OpType.Open);

            request.SessionMessage = session;
            GenericCommand response = await Connection.SendRequest(request);

            UpdateSession(response.SessionMessage);
            Connection.Register(Client);
        }
Exemplo n.º 18
0
        public override void ProcessCommand(SessionCommand sessionCommand)
        {
            switch (sessionCommand.CurrentCommand.CommandType)
            {
            case DataTypes.CommandType.None:
                Debugger.Print("Processing command: None");
                break;

            case DataTypes.CommandType.Login:
                Debugger.Print("Processing command: Login");
                MakerWOWApi.Login(sessionCommand, (string)sessionCommand.CurrentCommand.Arguments[0],
                                  (string)sessionCommand.CurrentCommand.Arguments[1], onLoginSuccess, onLoginFailed);
                break;

            case DataTypes.CommandType.Logout:
                Debugger.Print("Processing command: Logout");
                MakerWOWApi.Logout(sessionCommand, onLogoutSuccess, onLogoutFailed);
                break;

            case DataTypes.CommandType.StartWorld:
                Debugger.Print("Processing command: StartWorld");
                break;

            case DataTypes.CommandType.StopWorld:
                Debugger.Print("Processing command: StopWorld");
                break;

            case DataTypes.CommandType.World:
                Debugger.Print("Processing command: World");
                break;

            case DataTypes.CommandType.Lobby:
                Debugger.Print("Processing command: Lobby");
                foreach (var client in _clients.Values)
                {
                    _networkController.Networker.Send(client, sessionCommand.CurrentCommand.ToBytes());
                }
                break;

            case DataTypes.CommandType.Editor:
                Debugger.Print("Processing command: Editor");
                break;

            default:
                break;
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// 创建 Client
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="tag"></param>
        /// <param name="deviceId">设备唯一的 Id。如果是 iOS 设备,需要将 iOS 推送使用的 DeviceToken 作为 deviceId 传入</param>
        /// <param name="secure">是否强制加密 wss 链接</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <AVIMClient> CreateClientAsync(string clientId,
                                                   string tag      = null,
                                                   string deviceId = null,
                                                   bool secure     = true,
                                                   CancellationToken cancellationToken = default(CancellationToken))
        {
            lock (mutex)
            {
                var client = PreLogIn(clientId, tag, deviceId);

                AVRealtime.PrintLog("begin OpenAsync.");
                return(OpenAsync(secure, Subprotocol, cancellationToken).OnSuccess(t =>
                {
                    AVRealtime.PrintLog("OpenAsync OnSuccess. begin send open sesstion cmd.");

                    var cmd = new SessionCommand()
                              .UA(VersionString)
                              .Tag(tag)
                              .DeviceId(deviceId)
                              .Option("open")
                              .PeerId(clientId);

                    ToggleNotification(true);
                    return AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId));
                }).Unwrap().OnSuccess(x =>
                {
                    var cmd = x.Result;
                    return AVIMCommandRunner.RunCommandAsync(cmd);
                }).Unwrap().OnSuccess(s =>
                {
                    AVRealtime.PrintLog("sesstion opened.");
                    state = Status.Online;
                    ToggleHeartBeating(_heartBeatingToggle);
                    var response = s.Result.Item2;
                    if (response.ContainsKey("st"))
                    {
                        _sesstionToken = response["st"] as string;
                    }
                    if (response.ContainsKey("stTtl"))
                    {
                        var stTtl = long.Parse(response["stTtl"].ToString());
                        _sesstionTokenExpire = DateTime.Now.UnixTimeStampSeconds() + stTtl;
                    }
                    return client;
                }));
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// 重新打开会话
        /// </summary>
        /// <returns>The open session.</returns>
        internal Task ReOpenSession(string clientId)
        {
            var tcs         = new TaskCompletionSource <bool>();
            var sessionOpen = new SessionCommand();
            var cmd         = commandFactory.NewRequest(clientId, CommandType.Session, OpType.Open);

            cmd.sessionMessage = sessionOpen;
            SendRequest(cmd).ContinueWith(t => {
                AVRealtime.Context.Post(() => {
                    var res = t.Result;
                    // TODO 判断会话打开结果

                    tcs.SetResult(true);
                });
            });
            return(tcs.Task);
        }
Exemplo n.º 21
0
        internal Task LogInAsync(string clientId,
                                 string tag      = null,
                                 string deviceId = null,
                                 bool secure     = true,
                                 CancellationToken cancellationToken = default(CancellationToken))
        {
            lock (mutex)
            {
                var cmd = new SessionCommand()
                          .UA(VersionString)
                          .Tag(tag)
                          .DeviceId(deviceId)
                          .Option("open")
                          .PeerId(clientId);

                var result = AttachSignature(cmd, this.SignatureFactory.CreateConnectSignature(clientId)).OnSuccess(_ =>
                {
                    return(RunCommandAsync(cmd));
                }).Unwrap().OnSuccess(t =>
                {
                    AVRealtime.PrintLog("sesstion opened.");
                    if (t.Exception != null)
                    {
                        var imException = t.Exception.InnerException as AVIMException;
                        throw imException;
                    }
                    state        = Status.Online;
                    var response = t.Result.Item2;
                    if (response.ContainsKey("st"))
                    {
                        _sesstionToken = response["st"] as string;
                    }
                    if (response.ContainsKey("stTtl"))
                    {
                        var stTtl            = long.Parse(response["stTtl"].ToString());
                        _sesstionTokenExpire = DateTime.Now.ToUnixTimeStamp() + stTtl * 1000;
                    }
                    return(t.Result);
                });

                return(result);
            }
        }
Exemplo n.º 22
0
        public async Task <OutToken> Handle(SessionCommand command)
        {
            var user = await _userRepository.GetByUsername(command.Username);

            if (user == null)
            {
                throw new BusinessRuleValidationException("Usuário ou senha inválidos");
            }

            if (!BCrypt.Net.BCrypt.Verify(command.Password, user.Password))
            {
                throw new BusinessRuleValidationException("Usuário ou senha inválidos");
            }

            var token = TokenService.GenerateToken(user, _configuration);

            user.SetPasswordNull();

            return(new OutToken(token, user));
        }
Exemplo n.º 23
0
    /// <summary>
    /// Dodaje komendy do startowego CommandInvokera
    /// </summary>
    private void AddCommands()
    {
        SyncCommand sync0           = new SyncCommand(0);
        SyncCommand sync1           = new SyncCommand(1);
        Command     temporaryRoom   = new TemporaryRoomCommand();
        Command     subscribeEvents = new SubscribeEventsCommand(new List <IEventSubscribable>
        {
            instance,
            this.banking,
            this.session,
            menu,
            this.board,
            this.arController,
            this.flow,
            sync0,
            sync1
        });
        Command session            = new SessionCommand(this.session);
        Command board              = new BoardCommand(this.board);
        Command gameMenu           = new GameMenuCommand(menu);
        Command banking            = new BankingControllerCommand(this.banking);
        Command arController       = new ARControllerCommand(this.arController);
        Command gameplayController = new GameplayControllerCommand(instance);
        Command loadFromSave       = new LoadFromSaveCommand();
        Command popupSystem        = new PopupSystemCommand();

        invoker = new CommandInvoker(null, null, delegate { OnExecutionFinished(); sync0.UnsubscribeEvents(); sync1.UnsubscribeEvents(); });

        invoker.AddCommand(temporaryRoom);
        invoker.AddCommand(subscribeEvents);
        invoker.AddCommand(session);
        invoker.AddCommand(board);
        invoker.AddCommand(gameMenu);
        invoker.AddCommand(banking);
        invoker.AddCommand(gameplayController);
        invoker.AddCommand(loadFromSave);
        invoker.AddCommand(sync0);
        invoker.AddCommand(arController);
        invoker.AddCommand(popupSystem);
        invoker.AddCommand(sync1);
    }
Exemplo n.º 24
0
        private IResponse ResponseAnalizer(IResponse response, SessionCommand command)
        {
            switch (response.Status)
            {
            case ResponseStatus.Exception:
                return(new ButtonResponse(response.Text, GetCommands(), ResponseStatus.Expect));

            case ResponseStatus.Expect:
                ExpectedCommand = command;
                if (response is ButtonResponse)
                {
                    return(response);
                }
                return(new ButtonResponse(response.Text, GetCommands(), ResponseStatus.Expect));

            case ResponseStatus.Close:
                ExpectedCommand = null;
                return(new ButtonResponse(response.Text, GetCommands(), ResponseStatus.Expect));
            }
            return(response);
        }
Exemplo n.º 25
0
        public override void ProcessCommand(SessionCommand sessionCommand)
        {
            switch (sessionCommand.CurrentCommand.CommandType)
            {
            case DataTypes.CommandType.None:
                Debugger.Print("Processing command: None");
                break;

            case DataTypes.CommandType.Login:
                Debugger.Print("Processing command: Login");
                break;

            case DataTypes.CommandType.Logout:
                Debugger.Print("Processing command: Logout");
                break;

            case DataTypes.CommandType.StartWorld:
                Debugger.Print("Processing command: StartWorld");
                break;

            case DataTypes.CommandType.StopWorld:
                Debugger.Print("Processing command: StopWorld");
                break;

            case DataTypes.CommandType.World:
                Debugger.Print("Processing command: World");
                break;

            case DataTypes.CommandType.Lobby:
                Debugger.Print("Processing command: Lobby -> " + sessionCommand.CurrentCommand.Arguments[0]);
                break;

            case DataTypes.CommandType.Editor:
                Debugger.Print("Processing command: Editor");
                break;

            default:
                break;
            }
        }
Exemplo n.º 26
0
        internal Task OpenSessionAsync(string clientId,
                                       string tag       = null,
                                       string deviceId  = null,
                                       string nonce     = null,
                                       long timestamp   = 0,
                                       string signature = null,
                                       bool secure      = true)
        {
            var cmd = new SessionCommand()
                      .UA(VersionString)
                      .Tag(tag)
                      .DeviceId(deviceId)
                      .Option("open")
                      .PeerId(clientId)
                      .Argument("n", nonce)
                      .Argument("t", timestamp)
                      .Argument("s", signature);

            return(RunCommandAsync(cmd).OnSuccess(t =>
            {
                AVRealtime.PrintLog("sesstion opened.");
                if (t.Exception != null)
                {
                    var imException = t.Exception.InnerException as AVIMException;
                    throw imException;
                }
                state = Status.Online;
                var response = t.Result.Item2;
                if (response.ContainsKey("st"))
                {
                    _sesstionToken = response["st"] as string;
                }
                if (response.ContainsKey("stTtl"))
                {
                    var stTtl = long.Parse(response["stTtl"].ToString());
                    _sesstionTokenExpire = DateTime.Now.ToUnixTimeStamp() + stTtl * 1000;
                }
                return t.Result;
            }));
        }
Exemplo n.º 27
0
        public void Serialize()
        {
            GenericCommand command = new GenericCommand {
                Cmd    = CommandType.Session,
                Op     = OpType.Open,
                PeerId = "hello"
            };
            SessionCommand session = new SessionCommand {
                Code = 123
            };

            command.SessionMessage = session;
            byte[] bytes = command.ToByteArray();
            TestContext.WriteLine($"length: {bytes.Length}");

            command = GenericCommand.Parser.ParseFrom(bytes);
            Assert.AreEqual(command.Cmd, CommandType.Session);
            Assert.AreEqual(command.Op, OpType.Open);
            Assert.AreEqual(command.PeerId, "hello");
            Assert.NotNull(command.SessionMessage);
            Assert.AreEqual(command.SessionMessage.Code, 123);
        }
Exemplo n.º 28
0
        public static void Logout(SessionCommand sessionCommand,
                                  OnLogoutSuccessAction onLogoutSuccess, OnLogoutFailedAction onLogoutFailed)
        {
            var formData = new Dictionary <string, string>();

            DoPostRequest(formData, "account&process=logout",
                          (IWebRequest result) => {
                var apiResult = new ApiResult <ChunkDataJsonObject>(result.Json);
                if (apiResult.IsError)
                {
                    onLogoutFailed(sessionCommand, apiResult);
                }
                else
                {
                    _user = null;
                    onLogoutSuccess(sessionCommand, apiResult);
                }
            },
                          (WebContextException error) => {
                OnError(new ApiException(1, "Could not login, check error logs.", error));
            });
        }
Exemplo n.º 29
0
        internal async Task Reopen()
        {
            SessionCommand session = await NewSessionCommand();

            session.R = true;
            GenericCommand request = NewCommand(CommandType.Session, OpType.Open);

            request.SessionMessage = session;
            GenericCommand response = await Connection.SendRequest(request);

            if (response.Op == OpType.Opened)
            {
                UpdateSession(response.SessionMessage);
                Connection.Register(Client);
            }
            else if (response.Op == OpType.Closed)
            {
                Connection.UnRegister(Client);
                SessionCommand command = response.SessionMessage;
                throw new LCException(command.Code, command.Reason);
            }
        }
Exemplo n.º 30
0
        private async Task <SessionCommand> NewSessionCommand()
        {
            SessionCommand session = new SessionCommand();

            if (Client.Tag != null)
            {
                session.Tag = Client.Tag;
            }
            if (Client.DeviceId != null)
            {
                session.DeviceId = Client.DeviceId;
            }
            LCIMSignature signature = null;

            if (Client.SignatureFactory != null)
            {
                signature = await Client.SignatureFactory.CreateConnectSignature(Client.Id);
            }
            if (signature == null && !string.IsNullOrEmpty(Client.SessionToken))
            {
                Dictionary <string, object> ret = await LCCore.HttpClient.Post <Dictionary <string, object> >("rtm/sign", data : new Dictionary <string, object> {
                    { "session_token", Client.SessionToken }
                });

                signature = new LCIMSignature {
                    Signature = ret["signature"] as string,
                    Timestamp = (long)ret["timestamp"],
                    Nonce     = ret["nonce"] as string
                };
            }
            if (signature != null)
            {
                session.S = signature.Signature;
                session.T = signature.Timestamp;
                session.N = signature.Nonce;
            }
            return(session);
        }