Inheritance: GameState
Ejemplo n.º 1
0
        public void DdpClient_ConnectAsync_SetsSessionId()
        {
            var task = this.client.ConnectAsync();

            var connected = new Connected() {MessageType = "connected", Session = "TestSession"};
            this.testConnection.Reply(JsonConvert.SerializeObject(connected));

            task.Wait();

            Assert.AreEqual(this.client.SessionId, "TestSession", "Session should be set after successful connection.");
        }
Ejemplo n.º 2
0
        public void ConnectedResultFilter_HandleReturnObject_ConnectedMessage()
        {
            var connectedResultFilter = new ConnectedResultFilter();

            var connected = new Connected() {Session = "Test"};

            var returnedObject = new ReturnedObject("connected", JObject.FromObject(connected),
                JsonConvert.SerializeObject(connected));

            connectedResultFilter.HandleReturnObject(returnedObject);

            Assert.IsTrue(connectedResultFilter.IsCompleted());

            Assert.AreEqual(returnedObject, connectedResultFilter.GetReturnedObject());
        }
Ejemplo n.º 3
0
        public void ResultHandler_WaitForResult_WaitHandler()
        {
            var resultHandler = new ResultHandler();
            var waitHandle = resultHandler.RegisterWaitHandler(ResultFilterFactory.CreateConnectResultFilter());

            var waitTask = resultHandler.WaitForResult(waitHandle);

            var connected = new Connected() {Session = "TestSession"};
            var returnedObject = new ReturnedObject(connected.MessageType, JObject.FromObject(connected),
                JsonConvert.SerializeObject(connected));

            resultHandler.AddResult(returnedObject);

            waitTask.Wait();

            Assert.AreEqual(returnedObject, waitTask.Result);
        }
Ejemplo n.º 4
0
        public void ReplyMessageHandler_HandleMessage_HandlesConnected()
        {
            var connectionMock = new Mock<IDdpConnectionSender>();
            var collectionMock = new Mock<ICollectionManager>();
            var resultHandlerMock = new Mock<IResultHandler>();

            var connected = new Connected() {Session = "1"};

            var handler = new ReplyMessageHandler();

            handler.HandleMessage(connectionMock.Object, collectionMock.Object, resultHandlerMock.Object,
                JsonConvert.SerializeObject(connected));

            Assert.IsTrue(handler.CanHandle(connected.MessageType));

            resultHandlerMock.Verify(resultHandler => resultHandler.AddResult(It.IsAny<ReturnedObject>()));
        }
Ejemplo n.º 5
0
        public void DdpClient_ConnectAsync_SendsConnectMessage()
        {
            var task = this.client.ConnectAsync();

            var connected = new Connected() { MessageType = "connected", Session = "TestSession" };
            this.testConnection.Reply(JsonConvert.SerializeObject(connected));

            task.Wait();

            var message = this.testConnection.GetSentMessage();

            var connectMessage = JsonConvert.DeserializeObject<Connect>(message);

            Assert.IsNotNull(connectMessage, "Connect should send an object");
            Assert.AreEqual(connectMessage.Version, "1", "Message should support version 1");
            Assert.AreEqual(connectMessage.VersionsSupported.Count(), 1, "Client only supports 1 version");
            Assert.AreEqual(connectMessage.VersionsSupported.First(), "1", "Client only supports 1 version");
        }
Ejemplo n.º 6
0
        public void ResultHandler_RegisterResultCallback_CallbackCalled()
        {
            var resultHandler = new ResultHandler();

            bool callbackCalled = false;
            var connected = new Connected() { Session = "TestSession" };
            var returnedObject = new ReturnedObject(connected.MessageType, JObject.FromObject(connected),
                JsonConvert.SerializeObject(connected));

            resultHandler.RegisterResultCallback(ResultFilterFactory.CreateConnectResultFilter(), o =>
            {
                callbackCalled = true;
                Assert.AreEqual(returnedObject, o);
            });

            resultHandler.AddResult(returnedObject);

            Assert.IsTrue(callbackCalled);
        }
Ejemplo n.º 7
0
        public void ResultHandler_WaitForResult_ReactivateWaitHandle()
        {
            var resultHandler = new ResultHandler();
            var waitHandle = resultHandler.RegisterWaitHandler(ResultFilterFactory.CreateConnectResultFilter());

            var waitTask = resultHandler.WaitForResult(waitHandle);

            var connected = new Connected() { Session = "TestSession" };
            var returnedObject = new ReturnedObject(connected.MessageType, JObject.FromObject(connected),
                JsonConvert.SerializeObject(connected));

            resultHandler.AddResult(returnedObject);

            waitTask.Wait();

            Assert.AreEqual(returnedObject, waitTask.Result);

            PCLTesting.ExceptionAssert.Throws<InvalidOperationException>(() => resultHandler.WaitForResult(waitHandle));
        }
Ejemplo n.º 8
0
		public void PublishAsync_Where_No_Publication_Configurations_Which_Results_In_A_NoConfigurationFound_Result()
		{
			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _connectionManager = Substitute.For<IConnectionManager>();
			var _context = Substitute.For<IBusContext>();

			var _SUT = new Connected(
				_busConfirguration,
				_connectionManager,
				_context);

			var _theEvent = new MyEvent(Guid.NewGuid(), null, "Some detail", 1);
			var _publicationResult = _SUT.PublishAsync(_theEvent);
			_publicationResult.Wait();

			Assert.AreEqual(PMCG.Messaging.PublicationResultStatus.NoConfigurationFound, _publicationResult.Result.Status);
		}
Ejemplo n.º 9
0
 public static string ConnectedToStr(Connected con) {
   string ret = VisionLabPINVOKE.ConnectedToStr((int)con);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 10
0
 public static int RemoveGrayScaleBlobs(Int16Image image, Int16Image grayImage, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy, BlobAnalyseModifier baMod) {
   int ret = VisionLabPINVOKE.RemoveGrayScaleBlobs__SWIG_9(Int16Image.getCPtr(image), Int16Image.getCPtr(grayImage), (int)connected, (int)ba, low, high, (int)xy, BlobAnalyseModifier.getCPtr(baMod));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 11
0
 public static int FindSpecificGrayScaleHoles(Int32Image image, Int32Image grayImage, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy) {
   int ret = VisionLabPINVOKE.FindSpecificGrayScaleHoles__SWIG_13(Int32Image.getCPtr(image), Int32Image.getCPtr(grayImage), (int)connected, (int)ba, low, high, (int)xy);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 12
0
 public static bool FindCornersRectangle(Int16Image image, Connected connected, double deltaPhi, Orientation orient, XYCoord leftTop, XYCoord rigthTop, XYCoord leftBottom, XYCoord rightBottom) {
   bool ret = VisionLabPINVOKE.FindCornersRectangle__SWIG_3(Int16Image.getCPtr(image), (int)connected, deltaPhi, (int)orient, XYCoord.getCPtr(leftTop), XYCoord.getCPtr(rigthTop), XYCoord.getCPtr(leftBottom), XYCoord.getCPtr(rightBottom));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 13
0
 public static void BlobAnd(Int32Image image, Int32Image maskImage, Connected connected) {
   VisionLabPINVOKE.BlobAnd__SWIG_4(Int32Image.getCPtr(image), Int32Image.getCPtr(maskImage), (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 14
0
 public void OnConnected(NetConnection con, String message)
 {
     _awaitingActions.Enqueue(() => {
         Connected?.Invoke(this, new ConnectionEventArgs(default(UserHandle), message));
     });
 }
Ejemplo n.º 15
0
 protected bool Equals(Connected other)
 {
     return(Equals(_channel, other._channel));
 }
 private void FireConnected(TelemetryEventArgs e)
 {
     Connected?.Invoke(this, e);
 }
Ejemplo n.º 17
0
 internal void OnConnected()
 {
     Connected.SafeInvoke();
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Raises <see cref="Connected"/> event with specified <paramref name="authStatus"/> value.
 /// </summary>
 /// <param name="authStatus">Authentication status (protocol level) of client.</param>
 protected void OnConnected(
     AuthStatus authStatus) =>
 Connected?.Invoke(authStatus);
Ejemplo n.º 19
0
 public static int FindBlob(Int32Image src, Int32Image pat, Int32Image dest, Connected connected, float maxError, float beginAngle, float endAngle, int nrOfRotations) {
   int ret = VisionLabPINVOKE.FindBlob__SWIG_19(Int32Image.getCPtr(src), Int32Image.getCPtr(pat), Int32Image.getCPtr(dest), (int)connected, maxError, beginAngle, endAngle, nrOfRotations);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 20
0
 private void OnSessionConnected(object sender, RConnectedEventArgs e)
 => Connected?.Invoke(this, EventArgs.Empty);
Ejemplo n.º 21
0
 public static int FillSpecificGrayScaleHoles(ByteImage image, ByteImage grayImage, Connected connected, BlobAnalyse ba, double low, double high) {
   int ret = VisionLabPINVOKE.FillSpecificGrayScaleHoles__SWIG_5(ByteImage.getCPtr(image), ByteImage.getCPtr(grayImage), (int)connected, (int)ba, low, high);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 22
0
 private static void Client_Connected() => Connected?.Invoke();
Ejemplo n.º 23
0
 public static int FindSpecificHoles(Int16Image image, Connected connected, BlobAnalyse ba, double low, double high) {
   int ret = VisionLabPINVOKE.FindSpecificHoles__SWIG_11(Int16Image.getCPtr(image), (int)connected, (int)ba, low, high);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 24
0
 private void Connection_OnConnectSuccess(object sender, EventArgs e)
 {
     Connected.Fire(this, EventArgs.Empty);
 }
Ejemplo n.º 25
0
 public static void NrOfNeighbours(Int32Image src, Int32Image dest, Connected connected) {
   VisionLabPINVOKE.NrOfNeighbours__SWIG_4(Int32Image.getCPtr(src), Int32Image.getCPtr(dest), (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
 public PersonalPageDoctorViewModel(UsersInfoModel doctorInfoModel, CountMessageForPersonalPage countMessageForPersonalPage, Connected connected)
 {
     ConnectedID        = connected.ConnectedID;
     _connectionManager = new ConnectionManager();
     UserId             = doctorInfoModel.Id;
     FirstName          = doctorInfoModel.FirstName;
     LastName           = doctorInfoModel.LastName;
     DateOfBirthPatient = doctorInfoModel.DateOfBirth.UtcDateTime;
     PhoneNumber        = doctorInfoModel.PhoneNumber;
     Email = doctorInfoModel.Email;
     SelectDoctorCommand  = new DelegateCommand <InfoUserModel>(SelectDoctor);
     SelectPatientCommand = new DelegateCommand <InfoUserModel>(SelectPatient);
     DoctorsList          = new ObservableCollection <InfoUserModel>(doctorInfoModel.DortorsList);
     PatientsList         = new ObservableCollection <InfoUserModel>(doctorInfoModel.PatientsList);
     ButtonMessageCommand = new DelegateCommand(WriteMessageInChat);
     ActiveMessage(countMessageForPersonalPage.CountMessages);
 }
Ejemplo n.º 27
0
 public static void RemoveBorderBlobs(Int32Image image, Connected connected) {
   VisionLabPINVOKE.RemoveBorderBlobs__SWIG_9(Int32Image.getCPtr(image), (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 28
0
 private void Pipeclient_Connected(NamedPipeConnection <SAPEvent, SAPEvent> connection)
 {
     Connected?.Invoke();
 }
Ejemplo n.º 29
0
 public static void ZeroCrossings(DoubleImage src, DoubleImage dest, Connected con) {
   VisionLabPINVOKE.ZeroCrossings__SWIG_12(DoubleImage.getCPtr(src), DoubleImage.getCPtr(dest), (int)con);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 30
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="args"></param>
 private void Client_Connected(Sockets.EventArgs.SocketConnectedArgs args)
 {
     Connected?.Invoke();
 }
Ejemplo n.º 31
0
        public async Task ConnectAsync(string input, IBrowserProfile browserProfile)
        {
            CanConnect    = false;
            CanDisconnect = true;

            _disconnectReason = DisconnectReason.Unknown;
            InputType inputType;

            try
            {
                while (true)
                {
                    _first.Reset();
                    string liveId;
                    if (Tools.IsValidUserId(input))
                    {
                        inputType = InputType.UserId;
                        var userId = Tools.ExtractUserId(input);
                        liveId = await GetLiveIdAsync(userId);//TODO:

                        //GetLiveIdAsync()を実行中にユーザがDisconnect()するとliveIdがnullになる
                        if (string.IsNullOrEmpty(liveId))
                        {
                            break;
                        }
                    }
                    else if (Tools.IsValidLiveId(input))
                    {
                        inputType = InputType.LiveId;
                        liveId    = Tools.ExtractLiveId(input);
                    }
                    else
                    {
                        inputType = InputType.Unknown;
                        //
                        break;
                    }

                    var liveInfo = await Api.GetLiveInfo(_server, liveId);

                    MetadataUpdated?.Invoke(this, LiveInfo2Meta(liveInfo));
                    Connected?.Invoke(this, new ConnectedEventArgs
                    {
                        IsInputStoringNeeded = false,
                        UrlToRestore         = null,
                    });
                    var initialComments = await Api.GetLiveComments(_server, liveId);

                    foreach (var c in initialComments)
                    {
                        var userId         = c.UserId;
                        var isFirstComment = _first.IsFirstComment(userId);
                        var user           = GetUser(userId);

                        var context = CreateMessageContext(c, true, "");
                        MessageReceived?.Invoke(this, context);
                    }
                    _provider = CreateMessageProvider(liveInfo.Broadcastkey);
                    _provider.MessageReceived += Provider_MessageReceived;
                    _provider.MetadataUpdated += Provider_MetadataUpdated;

                    var commentTask  = _provider.ReceiveAsync();
                    var metaProvider = new MetadataProvider(_server, _siteOptions, liveId);
                    metaProvider.MetadataUpdated += MetaProvider_MetadataUpdated;
                    var metaTask = metaProvider.ReceiveAsync();
                    var tasks    = new List <Task>();
                    tasks.Add(commentTask);
                    tasks.Add(metaTask);

                    while (tasks.Count > 0)
                    {
                        var t = await Task.WhenAny(tasks);

                        if (t == commentTask)
                        {
                            try
                            {
                                await commentTask;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogException(ex, "", $"input={input}");
                            }
                            tasks.Remove(commentTask);
                            metaProvider.Disconnect();
                            try
                            {
                                await metaTask;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogException(ex, "", $"input={input}");
                            }
                            tasks.Remove(metaTask);
                        }
                        else if (t == metaTask)
                        {
                            try
                            {
                                await metaTask;
                            }
                            catch (Exception ex)
                            {
                                _logger.LogException(ex, "", $"input={input}");
                            }
                            tasks.Remove(metaTask);
                            //MetadataProviderの内部でcatchしないような例外が投げられた。メタデータの取得は諦めたほうが良い。多分。
                        }
                    }
                    //inputTypeがUserIdの場合は
                    if (inputType != InputType.UserId)
                    {
                        break;
                    }
                    if (_disconnectReason == DisconnectReason.User)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
            finally
            {
                CanConnect    = true;
                CanDisconnect = false;
            }
        }
Ejemplo n.º 32
0
        public async Task StartAsync(CancellationToken ct = default(CancellationToken))
        {
            if (_hasStarted)
            {
                throw new MorseLException($"Cannot call {nameof(StartAsync)} more than once.");
            }
            _hasStarted = true;

            ct.Register(() => _connectionCts.TrySetCanceled(ct));

            await Task.Run(async() =>
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                await _clientWebSocket.ConnectAsync(new Uri(_uri), ct).ConfigureAwait(false);
                stopwatch.Stop();

                _logger.LogDebug($"Connection to {_uri} established after {stopwatch.Elapsed.ToString("mm\\:ss\\.ff")}");

                _receiveLoopTask = Receive(async stream =>
                {
                    _logger.LogTrace($"Received message stream - beginning processing");
                    var message = await MessageSerializer.DeserializeAsync <Message>(stream, Encoding.UTF8).ConfigureAwait(false);
                    _logger.LogTrace($"Received \"{message}\"");

                    switch (message.MessageType)
                    {
                    case MessageType.ConnectionEvent:
                        _connectionCts.TrySetResult(null);

                        ConnectionId = message.Data;
                        Connected?.Invoke();
                        break;

                    case MessageType.ClientMethodInvocation:
                        InvocationDescriptor invocationDescriptor = null;
                        try
                        {
                            invocationDescriptor = MessageSerializer.DeserializeInvocationDescriptor(message.Data, _handlers);
                        }
                        catch (Exception exception)
                        {
                            await HandleUnparseableReceivedInvocationDescriptor(message.Data, exception).ConfigureAwait(false);
                            return;
                        }

                        if (invocationDescriptor == null)
                        {
                            // Valid JSON but unparseable into a known, typed invocation descriptor (unknown method name, invalid parameters)
                            await HandleInvalidReceivedInvocationDescriptor(message.Data).ConfigureAwait(false);
                            return;
                        }

                        await InvokeOn(invocationDescriptor).ConfigureAwait(false);
                        break;

                    case MessageType.InvocationResult:
                        InvocationResultDescriptor resultDescriptor;
                        try
                        {
                            resultDescriptor = MessageSerializer.DeserializeInvocationResultDescriptor(message.Data, _pendingCalls);
                        }
                        catch (Exception exception)
                        {
                            await HandleInvalidInvocationResultDescriptor(message.Data, exception).ConfigureAwait(false);
                            return;
                        }

                        HandleInvokeResult(resultDescriptor);
                        break;

                    case MessageType.Error:
                        await HandleErrorMessage(message).ConfigureAwait(false);
                        break;
                    }
                }, ct);
                _receiveLoopTask.ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        Error?.Invoke(task.Exception);
                    }
                });
            }, ct).ConfigureAwait(false);

            var timeoutTask = Task.Delay(_options.ConnectionTimeout);
            await Task.WhenAny(_connectionCts.Task, timeoutTask).ConfigureAwait(false);

            if (!ct.IsCancellationRequested && !_connectionCts.Task.IsCompleted && timeoutTask.IsCompleted)
            {
                throw new TimeoutException($"Connection attempt to {_uri} timed out after {_options.ConnectionTimeout}");
            }
        }
Ejemplo n.º 33
0
 public void Handler(Connected @event)
 {
     var controller = @event.AggregateGuid;
     var tenantId   = @event.Metadata.TenantId;
 }
Ejemplo n.º 34
0
 protected virtual void OnConnected(INetChannel channel)
 {
     Connected?.Invoke(this, new NetChannelArgs(channel));
 }
Ejemplo n.º 35
0
 private void HandleWebsocketOpened(object sender, EventArgs e)
 {
     ExecuteOnMainThread(() => { Connected?.Invoke(); });
 }
Ejemplo n.º 36
0
 protected virtual void OnConnected(EventArgs e)
 {
     Connected?.Invoke(this, e);
 }
Ejemplo n.º 37
0
        // Connection
        public static void Connect()
        {
            Disconnect();

            // Login
            string username = Account.Username, oauth = Account.OauthToken;

            try
            {
                if (Account.IsAnon)
                {
                    if (AppSettings.SelectedUser != "")
                    {
                        AppSettings.SelectedUser = "";
                        AppSettings.Save();
                    }
                }
                else
                {
                    if (!string.Equals(username, AppSettings.SelectedUser))
                    {
                        AppSettings.SelectedUser = username;
                        AppSettings.Save();
                    }
                }
            }
            catch
            {
            }

            LoggedIn?.Invoke(null, EventArgs.Empty);

            AppSettings.UpdateCustomHighlightRegex();

            // fetch ignored users
            //if (!Account.IsAnon)
            //{
            //    Task.Run(() =>
            //    {
            //        try
            //        {
            //            var limit = 100;
            //            var count = 0;
            //            string nextLink =
            //                $"https://api.twitch.tv/kraken/users/{username}/blocks?limit={limit}&client_id={Account.ClientId}";

            //            var request = WebRequest.Create(nextLink + $"&oauth_token={oauth}");
            //            if (AppSettings.IgnoreSystemProxy)
            //            {
            //                request.Proxy = null;
            //            }
            //            using (var response = request.GetResponse())
            //            using (var stream = response.GetResponseStream())
            //            {
            //                dynamic json = new JsonParser().Parse(stream);
            //                dynamic _links = json["_links"];
            //                nextLink = _links["next"];
            //                dynamic blocks = json["blocks"];
            //                count = blocks.Count;
            //                foreach (var block in blocks)
            //                {
            //                    dynamic user = block["user"];
            //                    string name = user["name"];
            //                    string display_name = user["display_name"];
            //                    twitchBlockedUsers[name] = null;
            //                }
            //            }
            //        }
            //        catch
            //        {
            //        }
            //    });
            //}

            // fetch available twitch emotes
            if (!Account.IsAnon)
            {
                Task.Run(() =>
                {
                    try
                    {
                        string uid = "";

                        var idReq =
                            WebRequest.Create($"https://api.twitch.tv/helix/users/?login={Account.Username}")
                            .AuthorizeHelix();
                        using (var resp = idReq.GetResponse())
                            using (var stream = resp.GetResponseStream())
                            {
                                dynamic json = new JsonParser().Parse(stream);
                                dynamic user = json["data"][0];
                                uid          = user["id"];
                            }

                        var request =
                            WebRequest.Create(
                                $"https://api.twitch.tv/kraken/users/{uid}/emotes")
                            .AuthorizeV5(oauth, Account.ClientId);

                        if (AppSettings.IgnoreSystemProxy)
                        {
                            request.Proxy = null;
                        }
                        using (var response = request.GetResponse())
                            using (var stream = response.GetResponseStream())
                            {
                                dynamic json = new JsonParser().Parse(stream);
                                Emotes.TwitchEmotes.Clear();

                                foreach (var set in json["emoticon_sets"])
                                {
                                    int setID;

                                    int.TryParse(set.Key, out setID);

                                    foreach (var emote in set.Value)
                                    {
                                        int id;

                                        int.TryParse(emote["id"], out id);

                                        string code = Emotes.GetTwitchEmoteCodeReplacement(emote["code"]);

                                        Emotes.TwitchEmotes[code] = new TwitchEmoteValue
                                        {
                                            ID          = id,
                                            Set         = setID,
                                            ChannelName = "<unknown>"
                                        };
                                    }
                                }
                            }
                    }
                    catch
                    {
                    }
                    Emotes.TriggerEmotesLoaded();
                });
            }

            // connect read
            Task.Run(() =>
            {
                Client = new IrcClient(Account.IsAnon);

                Client.ReadConnection.Connected += (s, e) =>
                {
                    foreach (var channel in TwitchChannel.Channels)
                    {
                        Client.ReadConnection.WriteLine("JOIN #" + channel.Name);
                    }

                    Connected?.Invoke(null, EventArgs.Empty);
                };

                Client.ReadConnection.Disconnected += (s, e) =>
                {
                    Disconnected?.Invoke(null, EventArgs.Empty);
                };

                if (!Account.IsAnon)
                {
                    Client.WriteConnection.Connected += (s, e) =>
                    {
                        foreach (var channel in TwitchChannel.Channels)
                        {
                            Client.WriteConnection.WriteLine("JOIN #" + channel.Name);
                        }
                    };
                }

                Client.Connect(username, (oauth.StartsWith("oauth:") ? oauth : "oauth:" + oauth));

                Client.ReadConnection.MessageReceived  += ReadConnection_MessageReceived;
                Client.WriteConnection.MessageReceived += WriteConnection_MessageReceived;
            });

            // secret telemetry, please ignore :)
            // anonymously count user on fourtf.com with the first 32 characters of a sha 256 hash of the username
            if (!Account.IsAnon)
            {
                Task.Run(() =>
                {
                    try
                    {
                        string hash;
                        using (var sha = SHA256.Create())
                        {
                            hash = string.Join("", sha
                                               .ComputeHash(Encoding.UTF8.GetBytes(username))
                                               .Select(item => item.ToString("x2")));
                        }
                        hash = hash.Remove(32);

                        var request = WebRequest.Create($"https://fourtf.com/chatterino/countuser.php?hash={hash}");
                        if (AppSettings.IgnoreSystemProxy)
                        {
                            request.Proxy = null;
                        }
                        using (var response = request.GetResponse())
                            using (response.GetResponseStream())
                            {
                            }
                    }
                    catch { }
                });
            }
        }
Ejemplo n.º 38
0
        public void Tick()
        {
            if (!_clientDriver.IsCreated)
            {
                return;
            }
            _clientDriver.ScheduleUpdate().Complete();

            if (_timeout > 0 && IsConnected && Time.time - LastPongTime > _timeout)
            {
                Debug.LogWarning("Disconnected due to timeout");
                Disconnect();
                return;
            }

            // listen for events
            NetworkEvent.Type eventType;
            while ((eventType = _clientToServerConnection.PopEvent(_clientDriver, out DataStreamReader streamReader))
                   != NetworkEvent.Type.Empty)
            {
                if (eventType == NetworkEvent.Type.Connect)
                {
                    Debug.Log("Connected!");
                    State = ClientState.Connected;
                    Connected?.Invoke();
                }
                else if (eventType == NetworkEvent.Type.Data)
                {
                    DataReceived?.Invoke(streamReader.Length);
                    int command = streamReader.ReadInt();
                    switch (command)
                    {
                    case Commands.AssignActorNumber:
                    {
                        ActorNumber = streamReader.ReadInt();
                        Debug.Log($"Got assigned actor number {ActorNumber}");
                        DataStreamWriter writer =
                            _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);
                        writer.WriteInt(Commands.AcknowledgeActorNumber);
                        _clientDriver.EndSend(writer);
                        DataSent?.Invoke(writer.Length);
                        break;
                    }

                    case Commands.AcceptPlayer:
                    {
                        DataStreamWriter writer =
                            _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection);
                        writer.WriteInt(Commands.RequestSpawnMessage);
                        writer.WriteInt(SceneManager.sceneCount);
                        for (var i = 0; i < SceneManager.sceneCount; i++)
                        {
                            writer.WriteInt(SceneManager.GetSceneAt(i).buildIndex);
                        }
                        SceneManager.sceneLoaded += OnSceneLoaded;
                        _clientDriver.EndSend(writer);
                        break;
                    }

                    case Commands.Ping:
                    {
                        LastPongTime = Time.time;
                        float sendLocalTime   = streamReader.ReadFloat();
                        float serverTime      = streamReader.ReadFloat();
                        float serverDeltaTime = streamReader.ReadFloat();
                        RoundTripTime = Time.time - sendLocalTime;
                        Latency       = IsHost
                                ? 0
                                : Mathf.Max(0, (RoundTripTime - serverDeltaTime / 2 - Time.deltaTime / 2) / 2);
                        // estimated server time NOW is received serverTime + latency for one trip + average frame wait on client side
                        float serverTimeOffset = serverTime - Time.time + Latency + Time.deltaTime / 2;
                        _averageServerTimeOffset = Mathf.Abs(_averageServerTimeOffset - serverTime) > 0.5f
                                ? serverTimeOffset
                                : 0.9f * _averageServerTimeOffset + 0.1f * serverTimeOffset;
                        PingReceived?.Invoke(RoundTripTime, Latency);
                        break;
                    }

                    case Commands.SpawnNetObjects:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int count = streamReader.ReadInt();

                        for (var i = 0; i < count; i++)
                        {
                            int        netObjID         = streamReader.ReadInt();
                            ushort     prefabIndex      = streamReader.ReadUShort();
                            int        ownerActorNumber = streamReader.ReadInt();
                            Vector3    position         = streamReader.ReadVector3();
                            Quaternion rotation         = streamReader.ReadQuaternion();
                            int        sceneBuildIndex  = streamReader.ReadInt();
                            int        size             = streamReader.ReadInt();
                            int        bytesRead        = streamReader.GetBytesRead();
                            Scene      scene            = SceneManager.GetSceneByBuildIndex(sceneBuildIndex);
                            var        deserialized     = false;
                            if (scene != null && scene.isLoaded)
                            {
                                NetObject netObject = NetObjectManager.Instance.SpawnOnClient(netObjID, prefabIndex,
                                                                                              ownerActorNumber, position, rotation, scene);
                                if (netObject != null)
                                {
                                    netObject.Deserialize(ref streamReader, behaviour => true);
                                    deserialized = true;
                                }
                            }

                            if (!deserialized)
                            {
                                streamReader.DiscardBytes(size);
                            }
                            if (streamReader.GetBytesRead() - bytesRead != size)
                            {
                                Debug.LogWarning("Did not deserialize properly!");
                            }
                        }

                        break;
                    }

                    case Commands.UpdateNetAssets:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int assetsInMessage = streamReader.ReadInt();
                        for (var i = 0; i < assetsInMessage; i++)
                        {
                            int assetNetID = streamReader.ReadInt();
                            int size       = streamReader.ReadInt();
                            int bytesRead  = streamReader.GetBytesRead();
                            try
                            {
                                NetAsset netAsset = NetAssetManager.Instance.Get(assetNetID);
                                netAsset.Deserialize(ref streamReader);
                            }
                            catch (Exception e)
                            {
                                Debug.LogException(new NetException($"Failed to update net asset {assetNetID}", e));
                                streamReader.DiscardBytes(size + bytesRead - streamReader.GetBytesRead());
                            }
                        }

                        break;
                    }

                    case Commands.UpdateNetObjects:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int objectsInMessage = streamReader.ReadInt();
                        for (var i = 0; i < objectsInMessage; i++)
                        {
                            int netObjID = streamReader.ReadInt();
                            int size     = streamReader.ReadInt();
                            if (NetObjectManager.Instance.Exists(netObjID))
                            {
                                NetObject netObject = NetObjectManager.Instance.Get(netObjID);
                                int       bytesRead = streamReader.GetBytesRead();
                                try
                                {
                                    netObject.Deserialize(ref streamReader, behaviour => !behaviour.HasAuthority);
                                }
                                catch (Exception e)
                                {
                                    Debug.LogException(
                                        new NetException($"Failed to update net object {netObjID}", e));
                                    streamReader.DiscardBytes(size + bytesRead - streamReader.GetBytesRead());
                                }
                            }
                            else
                            {
                                streamReader.DiscardBytes(size);
                            }
                        }

                        break;
                    }

                    case Commands.UnspawnNetObjects:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int count = streamReader.ReadInt();
                        for (var i = 0; i < count; i++)
                        {
                            int netObjID = streamReader.ReadInt();
                            NetObjectManager.Instance.Unspawn(netObjID);
                        }

                        break;
                    }

                    case Commands.GameAction:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        int   gameActionID = streamReader.ReadInt();
                        int   actorNumber  = streamReader.ReadInt();
                        float triggerTime  = streamReader.ReadFloat();
                        bool  valid        = streamReader.ReadBool();
                        try
                        {
                            GameAction             gameAction = GameActionManager.Instance.Get(gameActionID);
                            GameAction.IParameters parameters = gameAction.DeserializeParameters(ref streamReader);
                            gameAction.ReceiveOnClient(parameters, valid, actorNumber, triggerTime);
                            break;
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                            break;
                        }
                    }

                    case Commands.NetAssetRPC:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        float        sentServerTime = streamReader.ReadFloat();
                        int          netAssetID     = streamReader.ReadInt();
                        NetAsset     netAsset       = NetAssetManager.Instance.Get(netAssetID);
                        NetAsset.RPC rpc            = netAsset.DeserializeRPC(ref streamReader);
                        var          messageInfo    = new MessageInfo
                        {
                            SentServerTime = sentServerTime, SenderActorNumber = Server.ServerActorNumber
                        };
                        rpc.Invoke(messageInfo);
                        break;
                    }

                    case Commands.NetObjectRPC:
                    {
                        if (IsHost)
                        {
                            break;
                        }
                        float sentServerTime = streamReader.ReadFloat();
                        int   netObjectID    = streamReader.ReadInt();
                        if (!NetObjectManager.Instance.Exists(netObjectID))
                        {
                            Debug.LogWarning("Ignoring received RPC, because NetObject was not found.");
                            break;
                        }

                        NetObject            netObject      = NetObjectManager.Instance.Get(netObjectID);
                        ushort               netBehaviourID = streamReader.ReadUShort();
                        NetBehaviour         netBehaviour   = netObject.Get(netBehaviourID);
                        NetObjectManager.RPC rpc            =
                            NetObjectManager.Instance.DeserializeRPC(ref streamReader, netBehaviour);
                        var messageInfo = new MessageInfo
                        {
                            SentServerTime = sentServerTime, SenderActorNumber = Server.ServerActorNumber
                        };
                        rpc.Invoke(messageInfo);
                        break;
                    }

                    default:
                        Debug.LogError($"Unknown event type {eventType}");
                        break;
                    }
                }
                else if (eventType == NetworkEvent.Type.Disconnect)
                {
                    Debug.Log("Disconnected!");
                    SceneManager.sceneLoaded -= OnSceneLoaded;
                    Disconnected?.Invoke();
                    State = ClientState.Disconnected;
                    _clientToServerConnection = default;
                }
            }
        }
Ejemplo n.º 39
0
 public static int ApproxPolygon(Int32Image image, Connected connected, double minDistance, int maxVertices, vector_XYCoord tab) {
   int ret = VisionLabPINVOKE.ApproxPolygon__SWIG_4(Int32Image.getCPtr(image), (int)connected, minDistance, maxVertices, vector_XYCoord.getCPtr(tab));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Raises Connected event.
 /// </summary>
 protected virtual void OnConnected()
 {
     Connected?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 41
0
 public static void DistanceT(Int32Image image, Connected connected) {
   VisionLabPINVOKE.DistanceT__SWIG_8(Int32Image.getCPtr(image), (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 42
0
 private void OnInserted()
 {
     _attached = true;
     Connected?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 43
0
 public static int FindHoles(Int16Image image, Connected connected) {
   int ret = VisionLabPINVOKE.FindHoles__SWIG_3(Int16Image.getCPtr(image), (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 44
0
        private void Connect()
        {
#if DEBUG
            var ipAddresses = new List <IpAddressInfo>
            {
                new IpAddressInfo {
                    Ip = "192.168.178.114", Port = 10134
                },
                new IpAddressInfo {
                    Ip = "127.0.0.1", Port = 10134
                }
            };
#else
            var ipAddresses = Settings.GetBuilderProperty <ConnectionBuilderProperty>().IpAddresses;
#endif
            var currentIpIndex = 0;

            while (IsSearching)
            {
                var skip = false;

                foreach (var clientPlugin in PluginLoader.Current.ClientPlugins)
                {
                    try
                    {
                        if (!clientPlugin.CanTryConnect())
                        {
                            skip = true;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorReporter.Current.ReportError(ex, "CanStart() at plugin: \"" + clientPlugin.GetType() + "\"");
                    }
                }

                if (!skip)
                {
                    TcpClient    client       = null;
                    SslStream    stream       = null;
                    BinaryReader binaryReader = null;
                    BinaryWriter binaryWriter = null;

                    try
                    {
                        if (currentIpIndex >= ipAddresses.Count)
                        {
                            currentIpIndex = 0;
                        }

                        TryConnectDelegate connectFunction = TryConnect;
                        var connectionModifyingPlugin      =
                            PluginLoader.Current.ClientPlugins.FirstOrDefault(x => x.OverwriteTryConnect);
                        if (connectionModifyingPlugin != null)
                        {
                            connectFunction = connectionModifyingPlugin.TryConnect;
                        }

                        if (connectFunction(out client, out stream, ipAddresses[currentIpIndex]))
                        {
                            currentIpIndex = 0;
                            binaryWriter   = new BinaryWriter(stream);
                            binaryReader   = new BinaryReader(stream);

                            string path;
                            if (!Initialize(binaryWriter, binaryReader, out path))
                            {
                                stream.Dispose();
                                client.Close();

                                if (path != null)
                                {
                                    Program.Unload();
                                    var exeName   = Process.GetCurrentProcess().MainModule.FileName;
                                    var startInfo = new ProcessStartInfo(exeName)
                                    {
                                        Arguments = $"/wait /upgrade \"{path}\""
                                    };
                                    Process.Start(startInfo);
                                    Program.Exit();
                                }
                            }

                            if (Authenticate(binaryReader, binaryWriter))
                            {
                                InformationCollector.SendInformation(stream);
                                IsConnected = true;
                                StopConnect();
                                Connection = new ServerConnection(client, stream, binaryReader, binaryWriter,
                                                                  ClientOperator.Instance.DatabaseConnection, this);
                                Connection.Disconnected += Connection_Disconnected;
                                Connected?.Invoke(this, EventArgs.Empty);
                                break;
                            }
                        }
                        else
                        {
                            currentIpIndex++;
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    binaryReader?.Close();
                    binaryWriter?.Close();
                    stream?.Dispose();
                    client?.Close();
                }

                Thread.Sleep(Settings.GetBuilderProperty <ReconnectDelayProperty>().Delay + _random.Next(1, 340));
            }
        }
Ejemplo n.º 45
0
 public static bool FindCornersRectangleSq(Int32Image image, Connected connected, XYCoord leftTop, XYCoord rigthTop, XYCoord leftBottom, XYCoord rightBottom) {
   bool ret = VisionLabPINVOKE.FindCornersRectangleSq__SWIG_4(Int32Image.getCPtr(image), (int)connected, XYCoord.getCPtr(leftTop), XYCoord.getCPtr(rigthTop), XYCoord.getCPtr(leftBottom), XYCoord.getCPtr(rightBottom));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 46
0
 private void OnConnected(object sender, MqttClientConnectedEventArgs eventArgs)
 {
     Connected?.Invoke(this, eventArgs);
 }
Ejemplo n.º 47
0
 public static int FindSpecificHoles(Int32Image image, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy, BlobAnalyseModifier baMod) {
   int ret = VisionLabPINVOKE.FindSpecificHoles__SWIG_12(Int32Image.getCPtr(image), (int)connected, (int)ba, low, high, (int)xy, BlobAnalyseModifier.getCPtr(baMod));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 48
0
 public void OnConnected()
 {
     Connected?.Invoke(_quik, EventArgs.Empty);
 }
Ejemplo n.º 49
0
 public static int LabelBlobs(Int32Image image, Connected connected) {
   int ret = VisionLabPINVOKE.LabelBlobs__SWIG_4(Int32Image.getCPtr(image), (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 50
0
        public async Task <MqttClientConnectResult> ConnectAsync(IMqttClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (options.ChannelOptions == null)
            {
                throw new ArgumentException("ChannelOptions are not set.");
            }

            ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");

            try
            {
                Options = options;

                _packetIdentifierProvider.Reset();
                _packetDispatcher.Reset();

                _cancellationTokenSource = new CancellationTokenSource();
                _disconnectGate          = 0;
                _adapter = _adapterFactory.CreateClientAdapter(options, _logger);

                _logger.Verbose($"Trying to connect with server ({Options.ChannelOptions}).");
                await _adapter.ConnectAsync(Options.CommunicationTimeout, _cancellationTokenSource.Token).ConfigureAwait(false);

                _logger.Verbose("Connection with server established.");


                _packetReceiverTask = Task.Factory.StartNew(() => ReceivePacketsAsync(_cancellationTokenSource.Token),
                                                            _cancellationTokenSource.Token,
                                                            TaskCreationOptions.LongRunning,
                                                            TaskScheduler.Default).Unwrap();

                var connectResponse = await AuthenticateAsync(options.WillMessage, _cancellationTokenSource.Token).ConfigureAwait(false);

                _logger.Verbose("MQTT connection with server established.");

                _sendTracker.Restart();

                if (Options.KeepAlivePeriod != TimeSpan.Zero)
                {
                    StartSendingKeepAliveMessages(_cancellationTokenSource.Token);
                }

                IsConnected = true;

                Connected?.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.IsSessionPresent));

                _logger.Info("Connected.");
                return(new MqttClientConnectResult(connectResponse.IsSessionPresent));
            }
            catch (Exception exception)
            {
                _logger.Error(exception, "Error while connecting with server.");

                if (!DisconnectIsPending())
                {
                    await DisconnectInternalAsync(null, exception).ConfigureAwait(false);
                }

                throw;
            }
        }
Ejemplo n.º 51
0
 public static int RemoveBlobs(Int16Image image, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy) {
   int ret = VisionLabPINVOKE.RemoveBlobs__SWIG_10(Int16Image.getCPtr(image), (int)connected, (int)ba, low, high, (int)xy);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 52
0
 internal void RaiseConnected(string message)
 {
     Connected?.Invoke(message);
 }
Ejemplo n.º 53
0
 public static int RemoveGrayScaleBlobs(Int32Image image, Int32Image grayImage, Connected connected, BlobAnalyse ba, double low, double high) {
   int ret = VisionLabPINVOKE.RemoveGrayScaleBlobs__SWIG_14(Int32Image.getCPtr(image), Int32Image.getCPtr(grayImage), (int)connected, (int)ba, low, high);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 54
0
 /// <summary>
 /// To call the event <see cref="Connected"/>.
 /// </summary>
 private void RaiseConnected()
 {
     ConnectionState = ConnectionStates.Connected;
     Connected?.Invoke();
 }
Ejemplo n.º 55
0
 public static int SeparateBlobs(Int32Image src, Int32Image dest, Connected connected, int size) {
   int ret = VisionLabPINVOKE.SeparateBlobs__SWIG_4(Int32Image.getCPtr(src), Int32Image.getCPtr(dest), (int)connected, size);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Raises the Connected event.
 /// </summary>
 protected void OnConnected()
 {
     Connected?.Invoke();
 }
Ejemplo n.º 57
0
 public static void Canny(Int32Image src, Int32Image dest, double sigma, int low, int high, Connected connected) {
   VisionLabPINVOKE.Canny__SWIG_8(Int32Image.getCPtr(src), Int32Image.getCPtr(dest), sigma, low, high, (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 58
0
 internal void InvokeConnected()
 {
     Connected?.Invoke(this);
 }
Ejemplo n.º 59
0
 public static void ThresholdHysteresis(Int32Image image, int low, int high, Connected connected) {
   VisionLabPINVOKE.ThresholdHysteresis__SWIG_4(Int32Image.getCPtr(image), low, high, (int)connected);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
Ejemplo n.º 60
0
 private void WebSocket_Connected(IWebSocket obj)
 {
     Connected?.Invoke(this);
 }