Example #1
0
        private void PacketEvent(ConnectionContext ctx, ref Packet <C2S> packet)
        {
            if (ctx.WasExit)
            {
                return;
            }
            switch (packet.PacketType)
            {
            case PacketType.Command:
            case PacketType.CommandLow:
                var result = msgProc.PushMessage(packet.Data);
                if (result.HasValue)
                {
                    dispatcher.Invoke(result.Value);
                }
                break;

            case PacketType.Init1:
                if (packet.Data.Length >= 301 && packet.Data[4] == 4)
                {
                    initCheckDone = true;
                    var resultI = msgProc.PushMessage(packet.Data.AsMemory(301, packet.Data.Length - 301));
                    if (resultI.HasValue)
                    {
                        dispatcher.Invoke(resultI.Value);
                    }
                }
                break;
            }
        }
Example #2
0
        private void InvokeEvent(INotification notification)
        {
            // TODO rework
            switch (notification.NotifyType)
            {
            case NotificationType.ChannelCreated: break;

            case NotificationType.ChannelDeleted: break;

            case NotificationType.ChannelChanged: break;

            case NotificationType.ChannelEdited: break;

            case NotificationType.ChannelMoved: break;

            case NotificationType.ChannelPasswordChanged: break;

            case NotificationType.ClientEnterView: EventDispatcher.Invoke(() => ClientEnterViewHandler?.Invoke(this, (ClientEnterView)notification)); break;

            case NotificationType.ClientLeftView: EventDispatcher.Invoke(() => ClientLeftViewHandler?.Invoke(this, (ClientLeftView)notification)); break;

            case NotificationType.ClientMoved: break;

            case NotificationType.ServerEdited: break;

            case NotificationType.TextMessage: EventDispatcher.Invoke(() => TextMessageReceivedHandler?.Invoke(this, (TextMessage)notification)); break;

            case NotificationType.TokenUsed: break;

            default: throw new InvalidOperationException();
            }
        }
Example #3
0
        public void RemoveLines(LineViewModel[] lines)
        {
            foreach (var line in lines)
            {
                line.Cleanup();
                Lines.Remove(line);
            }

            _eventDispatcher.Invoke <ProjectChangedEvent>();
        }
Example #4
0
        private async Task PipeProcessorAsync(PipeReader reader, CancellationToken cancelationToken = default)
        {
            while (!cancelationToken.IsCancellationRequested)
            {
                var result = await reader.ReadAsync(cancelationToken).ConfigureAwait(false);

                var buffer = result.Buffer;
                SequencePosition?position;

                do
                {
                    position = buffer.PositionOf((byte)'\n');

                    if (position != null)
                    {
                        var notif = msgProc.PushMessage(buffer.Slice(0, position.Value).ToArray());
                        if (notif.HasValue)
                        {
                            dispatcher.Invoke(notif.Value);
                        }

                        // +2 = skipping \n\r
                        buffer = buffer.Slice(buffer.GetPosition(2, position.Value));
                    }
                } while (position != null);

                reader.AdvanceTo(buffer.Start, buffer.End);
                if (result.IsCompleted || result.IsCanceled)
                {
                    break;
                }
            }

            reader.Complete();
        }
Example #5
0
 private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
 {
     if (e.PropertyName == nameof(Line))
     {
         _eventDispatcher.Invoke <ProjectChangedEvent>();
     }
 }
Example #6
0
 protected void Update()
 {
     // Send an ExampleEvent if the specified key has been pressed (this can be done from any script which has access to this event dispatcher)
     if (Input.GetKeyDown(key))
     {
         eventDispatcher.Invoke(new ExampleEvent(key));
     }
 }
Example #7
0
        private void NetworkLoop()
        {
            while (true)
            {
                lock (statusLock)
                {
                    if (wasExit)
                    {
                        break;
                    }
                }
                if (wasExit)
                {
                    break;
                }

                IncomingPacket packet = packetHandler.FetchPacket();
                if (packet == null)
                {
                    break;
                }

                switch (packet.PacketType)
                {
                case PacketType.Command:
                case PacketType.CommandLow:
                    string message = Util.Encoder.GetString(packet.Data, 0, packet.Data.Length);
                    var    result  = msgProc.PushMessage(message);
                    if (result.HasValue)
                    {
                        dispatcher.Invoke(result.Value);
                    }
                    break;

                case PacketType.Voice:
                case PacketType.VoiceWhisper:
                    // VOICE

                    break;

                case PacketType.Init1:
                    var forwardData = ts3Crypt.ProcessInit1(packet.Data);
                    if (forwardData == null)
                    {
                        break;
                    }
                    packetHandler.AddOutgoingPacket(forwardData, PacketType.Init1);
                    break;
                }
            }

            lock (statusLock)
            {
                status = Ts3ClientStatus.Disconnected;
                DisconnectInternal();
            }
        }
Example #8
0
        private void PacketEvent(ConnectionContext ctx, ref Packet <S2C> packet)
        {
            lock (statusLock)
            {
                if (ctx.WasExit)
                {
                    return;
                }

                switch (packet.PacketType)
                {
                case PacketType.Command:
                case PacketType.CommandLow:
                    Log.ConditionalDebug("[I] {0}", Tools.Utf8Encoder.GetString(packet.Data));
                    var result = msgProc.PushMessage(packet.Data);
                    if (result.HasValue)
                    {
                        dispatcher.Invoke(result.Value);
                    }
                    break;

                case PacketType.Voice:
                case PacketType.VoiceWhisper:
                    OutStream?.Write(packet.Data, new Meta
                    {
                        In = new MetaIn
                        {
                            Whisper = packet.PacketType == PacketType.VoiceWhisper
                        }
                    });
                    break;

                case PacketType.Init1:
                    // Init error
                    if (packet.Data.Length == 5 && packet.Data[0] == 1)
                    {
                        var errorNum = BinaryPrimitives.ReadUInt32LittleEndian(packet.Data.AsSpan(1));
                        if (Enum.IsDefined(typeof(TsErrorCode), errorNum))
                        {
                            Log.Info("Got init error: {0}", (TsErrorCode)errorNum);
                        }
                        else
                        {
                            Log.Warn("Got undefined init error: {0}", errorNum);
                        }
                        DisconnectInternal(ctx, setStatus: TsClientStatus.Disconnected);
                    }
                    break;
                }
            }
        }
Example #9
0
        private async Task WriteLoopAsync(NetworkStream stream, PipeReader reader)
        {
            var dataWriteBuffer = new byte[4096];

            while (true)
            {
                var result = await reader.ReadAsync();

                ReadOnlySequence <byte> buffer   = result.Buffer;
                SequencePosition?       position = null;

                do
                {
                    position = buffer.PositionOf((byte)'\n');

                    if (position != null)
                    {
                        var notif = msgProc.PushMessage(buffer.Slice(0, position.Value).ToArray());
                        if (notif.HasValue)
                        {
                            dispatcher.Invoke(notif.Value);
                        }

                        // +2 = skipping \n\r
                        buffer = buffer.Slice(buffer.GetPosition(2, position.Value));
                    }
                } while (position != null);

                reader.AdvanceTo(buffer.Start, buffer.End);

                if (result.IsCompleted)
                {
                    break;
                }
            }

            reader.Complete();
        }
Example #10
0
 /// <summary>
 /// Static implementation of <see cref="EventDispatcher.Invoke(Type, object)"/>.
 /// </summary>
 /// <param name="type">The type of event.</param>
 /// <param name="evt">The event.</param>
 public static void Invoke(Type type, object evt)
 {
     eventDispatcher.Invoke(type, evt);
 }
 private void OnNewProject()
 {
     _eventDispatcher.Invoke(new ProjectEvent(ProjectEvent.InstructionType.New));
 }
Example #12
0
        private void NetworkLoop(object ctxObject)
        {
            var ctx = (ConnectionContext)ctxObject;

            while (true)
            {
                lock (statusLock)
                {
                    if (ctx.WasExit)
                    {
                        break;
                    }
                }

                var packet = packetHandler.FetchPacket();
                if (packet == null)
                {
                    break;
                }

                lock (statusLock)
                {
                    if (ctx.WasExit)
                    {
                        break;
                    }

                    switch (packet.PacketType)
                    {
                    case PacketType.Command:
                    case PacketType.CommandLow:
                        string message = Util.Encoder.GetString(packet.Data, 0, packet.Data.Length);
                        LogCmd.Debug("[I] {0}", message);
                        var result = msgProc.PushMessage(message);
                        if (result.HasValue)
                        {
                            dispatcher.Invoke(result.Value);
                        }
                        break;

                    case PacketType.Voice:
                    case PacketType.VoiceWhisper:
                        OutStream?.Write(packet.Data, new Meta
                        {
                            In = new MetaIn
                            {
                                Whisper = packet.PacketType == PacketType.VoiceWhisper
                            }
                        });
                        break;

                    case PacketType.Init1:
                        // Init error
                        if (packet.Data.Length == 5 && packet.Data[0] == 1)
                        {
                            var errorNum = BinaryPrimitives.ReadUInt32LittleEndian(packet.Data.AsReadOnlySpan().Slice(1));
                            if (Enum.IsDefined(typeof(Ts3ErrorCode), errorNum))
                            {
                                Log.Info("Got init error: {0}", (Ts3ErrorCode)errorNum);
                            }
                            else
                            {
                                Log.Warn("Got undefined init error: {0}", errorNum);
                            }
                            DisconnectInternal(ctx, setStatus: Ts3ClientStatus.Disconnected);
                        }
                        break;
                    }
                }
            }

            lock (statusLock)
            {
                DisconnectInternal(ctx, setStatus: Ts3ClientStatus.Disconnected);
            }
        }
Example #13
0
 private void OnAddCard()
 {
     _eventDispatcher.Invoke <AddCardEvent>();
 }
Example #14
0
        private void ReceiveResponse(RecordedDataSourceSelectorEventArgs e)
        {
            if (e == null)
            {
                throw new InvalidOperationException("Somehow lost required state argument!");
            }

            DebugLog.WriteCoreLine("~~~> Waiting for stubbed response" + (string.IsNullOrEmpty(_url) ? string.Empty : string.Concat(" (", _url, ")")));

            InternalPreSelectResponse(e);

            // allow external code to select the next response,
            // if there is no handler, automatically next one from the list will be taken:
            Event.Invoke(SelectResponse, this, e);

            SelectedIndex = e.NextResponseIndex;
            var response = e.SelectedResponse;

            if (response == null)
            {
                DebugLog.WriteCoreLine("Missing response object!");

                _isActive = false;
                _eventDispatcher.Invoke(DataReceiveFailed, this, new HttpDataSourceEventArgs(this, HttpStatusCode.NotFound, "Not found response object, the request was adressed for"));
                return;
            }

            if (VerifyIfCancelled())
            {
                return;
            }

            // now wait time specified inside the response:
            if (response.Delay > 0)
            {
                if (response.Delay > Timeout)
                {
                    Thread.Sleep(Timeout);
                    if (VerifyIfCancelled())
                    {
                        return;
                    }

                    _isActive = false;
                    DebugLog.WriteCoreLine(string.Concat("--> Request timeouted (data-source timeout: ", Timeout, " ms, response delay: ", response.Delay, " ms)!"));
                    _eventDispatcher.Invoke(DataReceiveFailed, this, new HttpDataSourceEventArgs(this, HttpStatusCode.RequestTimeout, "Request timeouted due to huge response delay"));
                    return;
                }

                Thread.Sleep(response.Delay);
                if (VerifyIfCancelled())
                {
                    return;
                }

                _isActive = false;
            }

            InternalPreProcessResponse(e);

            DebugLog.WriteCoreLine(string.Format(CultureInfo.InvariantCulture, "---> Received response (length: {0} bytes, at: {1}, waiting: {2:F2} sec) with status: {3} ({4}, {5}, {6})",
                                                 response.Length, DateTime.Now, (DateTime.Now - e.SentAt).TotalSeconds, response.StatusCode, (int)response.StatusCode, response.StatusDescription, response.ContentType));

            string category = string.Concat(DebugLog.CategoryCore, ".HttpDataSource.Receive", string.IsNullOrEmpty(response.ContentType) ? string.Empty : ".", response.ContentType);

            if (response.Length == 0)
            {
                DebugLog.WriteCoreLine(NothingContentDescription);
            }
            else if (response.AsString != null)
            {
                DebugLog.WriteLine(category, response.AsString);
            }
            else
            {
                DebugLog.WriteLine(category, BinaryContentDescription);
            }

            switch (e.ResponseType)
            {
            case HttpDataSourceResponseType.AsString:
                _eventDispatcher.Invoke(response.IsFailure ? DataReceiveFailed : DataReceived, this, new HttpDataSourceEventArgs(this, response.StatusCode, response.StatusDescription, response.AsString, null, null));
                return;

            case HttpDataSourceResponseType.AsBinary:
                _eventDispatcher.Invoke(response.IsFailure ? DataReceiveFailed : DataReceived, this, new HttpDataSourceEventArgs(this, response.StatusCode, response.StatusDescription, null, response.AsBinary, null));
                return;

            case HttpDataSourceResponseType.AsRawStream:
                using (var stream = new MemoryStream(response.AsBinary ?? new byte[0]))
                {
                    _eventDispatcher.Invoke(response.IsFailure ? DataReceiveFailed : DataReceived, this, new HttpDataSourceEventArgs(this, response.StatusCode, response.StatusDescription, null, null, stream));
                }
                return;

            default:
                throw new NotImplementedException("Invalid response type requested");
            }
        }