Exemplo n.º 1
0
        /// <summary> Creates a new REST-only Discord client. </summary>
        internal BaseDiscordClient(DiscordRestConfig config, API.DiscordRestApiClient client)
        {
            ApiClient           = client;
            LogManager          = new LogManager(config.LogLevel);
            LogManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);

            _stateLock    = new SemaphoreSlim(1, 1);
            _restLogger   = LogManager.CreateLogger("Rest");
            _isFirstLogin = config.DisplayInitialLog;

            UseInteractionSnowflakeDate = config.UseInteractionSnowflakeDate;

            ApiClient.RequestQueue.RateLimitTriggered += async(id, info, endpoint) =>
            {
                if (info == null)
                {
                    await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false);
                }
                else
                {
                    await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false);
                }
            };
            ApiClient.SentRequest += async(method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false);
        }
Exemplo n.º 2
0
        private async Task LoginInternalAsync(TokenType tokenType, string token)
        {
            if (_isFirstLogin)
            {
                _isFirstLogin = false;
                await LogManager.WriteInitialLog().ConfigureAwait(false);
            }

            if (LoginState != LoginState.LoggedOut)
            {
                await LogoutInternalAsync().ConfigureAwait(false);
            }
            LoginState = LoginState.LoggingIn;

            try
            {
                await ApiClient.LoginAsync(tokenType, token).ConfigureAwait(false);
                await OnLoginAsync(tokenType, token).ConfigureAwait(false);

                LoginState = LoginState.LoggedIn;
            }
            catch (Exception)
            {
                await LogoutInternalAsync().ConfigureAwait(false);

                throw;
            }

            await _loggedInEvent.InvokeAsync().ConfigureAwait(false);
        }
        private async Task <TResponse> SendRpcAsyncInternal <TResponse>(string cmd, object payload, Optional <string> evt, RequestOptions options)
            where TResponse : class
        {
            byte[] bytes = null;
            var    guid  = Guid.NewGuid();

            payload = new API.Rpc.RpcFrame {
                Cmd = cmd, Event = evt, Args = payload, Nonce = guid
            };
            if (payload != null)
            {
                var json = SerializeJson(payload);
                bytes = Encoding.UTF8.GetBytes(json);
            }

            var requestTracker = new RpcRequest <TResponse>(options);

            _requests[guid] = requestTracker;

            await RequestQueue.SendAsync(new WebSocketRequest(_webSocketClient, null, bytes, true, options)).ConfigureAwait(false);

            await _sentRpcMessageEvent.InvokeAsync(cmd).ConfigureAwait(false);

            return(await requestTracker.Promise.Task.ConfigureAwait(false));
        }
Exemplo n.º 4
0
 internal async Task CallOnMessageAsync(string result)
 {
     await _on_message.InvokeAsync(new SocketMessageEventArgs()
     {
         Message = result
     });
 }
Exemplo n.º 5
0
        public TwitchPubsubApiClient(RestClientProvider restClientProvider, SocketClientProvider socketClientProvider, string clientId, string userAgent,
                                     string webSocketUrl, RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializer serializer = null)
            : base(restClientProvider, clientId, userAgent, serializer)
        {
            _webSocketUrl   = webSocketUrl;
            WebSocketClient = socketClientProvider() as IWebSocketClient;
            _callbacks      = new ConcurrentDictionary <string, Func <PubsubFrame <string>, Task> >();

            WebSocketClient.TextMessage += async text =>
            {
                using (var reader = new StringReader(text))
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        var msg = _serializer.Deserialize <PubsubFrame <string> >(jsonReader);
                        if (msg != null)
                        {
                            await _receivedPubsubEvent.InvokeAsync(msg).ConfigureAwait(false);
                        }
                    }
            };
            WebSocketClient.Closed += async ex =>
            {
                await DisconnectAsync().ConfigureAwait(false);

                await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
            };
        }
Exemplo n.º 6
0
        private async Task DisconnectInternalAsync(Exception ex)
        {
            if (ConnectionState == ConnectionState.Disconnected)
            {
                return;
            }
            ConnectionState = ConnectionState.Disconnecting;
            await _audioLogger.InfoAsync("Disconnecting").ConfigureAwait(false);

            //Signal tasks to complete
            try { _cancelToken.Cancel(); } catch { }

            //Disconnect from server
            await ApiClient.DisconnectAsync().ConfigureAwait(false);

            //Wait for tasks to complete
            var heartbeatTask = _heartbeatTask;

            if (heartbeatTask != null)
            {
                await heartbeatTask.ConfigureAwait(false);
            }
            _heartbeatTask = null;

            ConnectionState = ConnectionState.Disconnected;
            await _audioLogger.InfoAsync("Disconnected").ConfigureAwait(false);

            await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
        }
Exemplo n.º 7
0
        private async Task <System.IO.Stream> SendInternalAsync(string method, string endpoint, RestRequest request)
        {
            if (!request.Options.IgnoreState)
            {
                CheckLoginState();
            }
            //if (request.Options.RetryMode == null)
            //    request.Options.RetryMode = DefaultRetryMode;

            var stopwatch = Stopwatch.StartNew();
            var response  = await request.SendAsync().ConfigureAwait(false);

            stopwatch.Stop();

            double milliseconds = ToMilliseconds(stopwatch);
            await _sentRequestEvent.InvokeAsync(method, endpoint, milliseconds).ConfigureAwait(false);

            switch ((int)response.StatusCode)
            {
            case 200:      // Ok
                break;

            case 204:      // No Content
            case 400:      // Bad Request
            case 401:      // Unauthorized
            case 404:      // Not found
            case 422:      // Unprocessable Entity
            default:       // Unrecognized code
                var error = DeserializeJson <Error>(response.Body);
                throw new HttpException(response.StatusCode, error.GetErrorMessage().Message);
            }

            return(response.Body);
        }
Exemplo n.º 8
0
        private async Task OnDocumentsSavedAsync(ICollection <T> documents, ICollection <T> originalDocuments, bool sendNotifications)
        {
            var modifiedDocs = originalDocuments.FullOuterJoin(
                documents, cf => cf.Id, cf => cf.Id,
                (original, modified, id) => new { Id = id, Original = original, Modified = modified }).Select(m => new ModifiedDocument <T>(m.Modified, m.Original)).ToList();

            // if we couldn't find an original document, then it must be new.
            var addedDocs = modifiedDocs.Where(m => m.Original == null).Select(m => m.Value).ToList();

            if (addedDocs.Count > 0)
            {
                await OnDocumentsAddedAsync(addedDocs, sendNotifications).AnyContext();
            }

            var savedDocs = modifiedDocs.Where(m => m.Original != null).ToList();

            if (savedDocs.Count == 0)
            {
                return;
            }

            if (DocumentsSaved != null)
            {
                await DocumentsSaved.InvokeAsync(this, new ModifiedDocumentsEventArgs <T>(modifiedDocs, this)).AnyContext();
            }

            await OnDocumentsChangedAsync(ChangeType.Saved, savedDocs).AnyContext();

            if (sendNotifications)
            {
                await SendNotificationsAsync(ChangeType.Saved, savedDocs).AnyContext();
            }
        }
Exemplo n.º 9
0
        private async Task SendGatewayInternalAsync(GatewayOpCode opCode, object payload, RequestOptions options)
        {
            CheckState();

            //TODO: Add ETF
            byte[] bytes = null;
            payload = new SocketFrame {
                Operation = (int)opCode, Payload = payload
            };
            if (payload != null)
            {
                bytes = Encoding.UTF8.GetBytes(SerializeJson(payload));
            }

            options.IsGatewayBucket = true;
            if (options.BucketId == null)
            {
                options.BucketId = GatewayBucket.Get(GatewayBucketType.Unbucketed).Id;
            }
            await RequestQueue.SendAsync(new WebSocketRequest(WebSocketClient, bytes, true, opCode == GatewayOpCode.Heartbeat, options)).ConfigureAwait(false);

            await _sentGatewayMessageEvent.InvokeAsync(opCode).ConfigureAwait(false);

#if DEBUG_PACKETS
            Console.WriteLine($"-> {opCode}:\n{SerializeJson(payload)}");
#endif
        }
Exemplo n.º 10
0
        private void ChatMessageEvetRiser()
        {
            Task.Factory.StartNew(async() =>
            {
                if (_FFChatMessageArrived.HandlersCount == 0)
                {
                    SpinWait.SpinUntil(() => _FFChatMessageArrived.HandlersCount > 0);
                }

                while (_KeepWorking)
                {
                    try
                    {
                        FFChatMsg ffChatMsg = new FFChatMsg();
                        if (_FFxivChat.TryDequeue(out ffChatMsg))
                        {
                            var ea = new ChatMessageArrivedEventArgs(this)
                            {
                                ChatMessage = ffChatMsg
                            };

                            await _FFChatMessageArrived.InvokeAsync(ea);
                        }
                        else
                        {
                            SpinWait.SpinUntil(() => _FFxivChat.IsEmpty == false && _KeepWorking == true);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.WriteLog(e);
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
        private void OnGlobalHotKeyPressed(object sender, GlobalHotKeyEventArgs e)
        {
            if (ShowHideChatKeys != null)
            {
                if (e.HotKey.Name == ShowHideChatKeys.Name)
                {
                    if (this.IsWindowVisible)
                    {
                        IsHiddenByUser = true;
                    }
                    else
                    {
                        IsHiddenByUser = false;
                    }

                    IsWindowVisible = !IsWindowVisible;
                }
            }
            if (ClickThoughtChatKeys != null)
            {
                if (e.HotKey.Name == ClickThoughtChatKeys.Name)
                {
                    IsClickThrough = !IsClickThrough;
                }
            }
            if (ClearChatKeys != null)
            {
                if (e.HotKey.Name == ClearChatKeys.Name)
                {
                    _RequestChatClear.InvokeAsync(new TatruEventArgs(this));
                }
            }
        }
        private async Task OnBeforeQueryAsync(IRepositoryQuery query, ICommandOptions options, Type resultType)
        {
            if (SupportsSoftDeletes && IsCacheEnabled && options.GetSoftDeleteMode() == SoftDeleteQueryMode.ActiveOnly)
            {
                var deletedIds = await Cache.GetListAsync <string>("deleted").AnyContext();

                if (deletedIds.HasValue)
                {
                    query.ExcludedId(deletedIds.Value);
                }
            }

            var systemFilter = query.GetSystemFilter();

            if (systemFilter != null)
            {
                query.MergeFrom(systemFilter.GetQuery());
            }

            if (BeforeQuery == null || !BeforeQuery.HasHandlers)
            {
                return;
            }

            await BeforeQuery.InvokeAsync(this, new BeforeQueryEventArgs <T>(query, options, this, resultType)).AnyContext();
        }
        /// <summary> Creates a new Webhook discord client. </summary>
        public DiscordWebhookClient(ulong webhookId, string webhookToken, DiscordRestConfig config)
        {
            _webhookId = webhookId;

            ApiClient           = CreateApiClient(config);
            LogManager          = new LogManager(config.LogLevel);
            LogManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);

            _restLogger = LogManager.CreateLogger("Rest");

            ApiClient.RequestQueue.RateLimitTriggered += async(id, info) =>
            {
                if (info == null)
                {
                    await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {id ?? "null"}").ConfigureAwait(false);
                }
                else
                {
                    await _restLogger.WarningAsync($"Rate limit triggered: {id ?? "null"}").ConfigureAwait(false);
                }
            };
            ApiClient.SentRequest += async(method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false);

            ApiClient.LoginAsync(TokenType.Webhook, webhookToken).GetAwaiter().GetResult();
        }
Exemplo n.º 14
0
        protected virtual async Task OnCompletedAsync(IQueueEntry <T> entry)
        {
            var now = SystemClock.UtcNow;

            LastDequeueActivity = now;

            if (entry is QueueEntry <T> metadata)
            {
                if (metadata.EnqueuedTimeUtc > DateTime.MinValue)
                {
                    metadata.TotalTime = now.Subtract(metadata.EnqueuedTimeUtc);
                }

                if (metadata.DequeuedTimeUtc > DateTime.MinValue)
                {
                    metadata.ProcessingTime = now.Subtract(metadata.DequeuedTimeUtc);
                }
            }

            if (Completed != null)
            {
                var args = new CompletedEventArgs <T> {
                    Queue = this, Entry = entry
                };
                await Completed.InvokeAsync(this, args).AnyContext();
            }

            StopProcessQueueEntryActivity(entry);
        }
Exemplo n.º 15
0
        private async Task ProcessVoicePacket(byte[] data)
        {
            if (data.Length < 13) // minimum packet length
            {
                return;
            }

            try
            {
                var pcm        = new byte[AudioFormat.CalculateMaximumFrameSize()];
                var pcmMem     = pcm.AsMemory();
                var opus       = new byte[pcm.Length];
                var opusMem    = opus.AsMemory();
                var pcmFillers = new List <ReadOnlyMemory <byte> >();
                if (!ProcessPacket(data, ref opusMem, ref pcmMem, pcmFillers, out var vtx, out var audioFormat))
                {
                    return;
                }

                foreach (var pcmFiller in pcmFillers)
                {
                    await _voiceReceived.InvokeAsync(new VoiceReceiveEventArgs(Discord)
                    {
                        SSRC          = vtx.SSRC,
                        UserId        = vtx.UserId,
                        PcmData       = pcmFiller,
                        OpusData      = new byte[0].AsMemory(),
                        AudioFormat   = audioFormat,
                        AudioDuration = audioFormat.CalculateSampleDuration(pcmFiller.Length)
                    }).ConfigureAwait(false);
                }

                await _voiceReceived.InvokeAsync(new VoiceReceiveEventArgs(Discord)
                {
                    SSRC          = vtx.SSRC,
                    UserId        = vtx.UserId,
                    PcmData       = pcmMem,
                    OpusData      = opusMem,
                    AudioFormat   = audioFormat,
                    AudioDuration = audioFormat.CalculateSampleDuration(pcmMem.Length)
                }).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Discord.DebugLogger.LogMessage(LogLevel.Error, "VNext RX", "Exception occured when decoding incoming audio data", DateTime.Now, ex);
            }
        }
        public DiscordSocketApiClient(RestClientProvider restClientProvider, WebSocketProvider webSocketProvider, string userAgent,
            string url = null, RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializer serializer = null,
            RateLimitPrecision rateLimitPrecision = RateLimitPrecision.Second,
			bool useSystemClock = true)
            : base(restClientProvider, userAgent, defaultRetryMode, serializer, rateLimitPrecision, useSystemClock)
        {
            _gatewayUrl = url;
            if (url != null)
                _isExplicitUrl = true;
            WebSocketClient = webSocketProvider();
            //WebSocketClient.SetHeader("user-agent", DiscordConfig.UserAgent); (Causes issues in .NET Framework 4.6+)

            WebSocketClient.BinaryMessage += async (data, index, count) =>
            {
                using (var decompressed = new MemoryStream())
                {
                    if (data[0] == 0x78)
                    {
                        //Strip the zlib header
                        _compressed.Write(data, index + 2, count - 2);
                        _compressed.SetLength(count - 2);
                    }
                    else
                    {
                        _compressed.Write(data, index, count);
                        _compressed.SetLength(count);
                    }

                    //Reset positions so we don't run out of memory
                    _compressed.Position = 0;
                    _decompressor.CopyTo(decompressed);
                    _compressed.Position = 0;
                    decompressed.Position = 0;

                    using (var reader = new StreamReader(decompressed))
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        var msg = _serializer.Deserialize<SocketFrame>(jsonReader);
                        if (msg != null)
                            await _receivedGatewayEvent.InvokeAsync((GatewayOpCode)msg.Operation, msg.Sequence, msg.Type, msg.Payload).ConfigureAwait(false);
                    }
                }
            };
            WebSocketClient.TextMessage += async text =>
            {
                using (var reader = new StringReader(text))
                using (var jsonReader = new JsonTextReader(reader))
                {
                    var msg = _serializer.Deserialize<SocketFrame>(jsonReader);
                    if (msg != null)
                        await _receivedGatewayEvent.InvokeAsync((GatewayOpCode)msg.Operation, msg.Sequence, msg.Type, msg.Payload).ConfigureAwait(false);
                }
            };
            WebSocketClient.Closed += async ex =>
            {
                await DisconnectAsync().ConfigureAwait(false);
                await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
            };
        }
        private void OnPropertyChanged([CallerMemberName] string prop = "")
        {
            var ea = new AsyncPropertyChangedEventArgs(this, prop);

            _AsyncPropertyChanged.InvokeAsync(ea).Forget();

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }
Exemplo n.º 18
0
        public async Task SendAsync(byte[] data, int bytes)
        {
            if (_udpEndpoint != null)
            {
                await _udp.SendAsync(data, bytes, _udpEndpoint).ConfigureAwait(false);

                await _sentDataEvent.InvokeAsync(bytes).ConfigureAwait(false);
            }
        }
Exemplo n.º 19
0
        public async void AsyncEventSyncHandler()
        {
            var counter = 0;

            void MyMethod() => counter++;

            var ev = new AsyncEvent <EventArgs>();

            ev.Subscribe(MyMethod);
            await ev.InvokeAsync(this, new EventArgs());

            Assert.Equal(1, counter);

            ev.Unsubscribe(MyMethod);
            await ev.InvokeAsync(this, new EventArgs());

            Assert.Equal(1, counter);
        }
Exemplo n.º 20
0
        private async Task OnDocumentsChangedAsync(ChangeType changeType, ICollection <ModifiedDocument <T> > documents)
        {
            if (DocumentsChanged == null)
            {
                return;
            }

            await DocumentsChanged.InvokeAsync(this, new DocumentsChangeEventArgs <T>(changeType, documents, this)).AnyContext();
        }
Exemplo n.º 21
0
        internal BaseTwitchClient(TwitchConfig config, TwitchRestApiClient client)
        {
            ApiClient           = client;
            LogManager          = new LogManager(config.LogLevel);
            LogManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);

            _stateLock             = new SemaphoreSlim(1, 1);
            RestLogger             = LogManager.CreateLogger("Rest");
            ApiClient.SentRequest += async(method, endpoint, ms) => await RestLogger.VerboseAsync($"{method} /{endpoint}: {ms} ms");
        }
Exemplo n.º 22
0
        public async Task SendSocketAsync(string command, string parameters, string tags = null, RequestOptions options = null)
        {
            CheckLoginState();
            options = options ?? new RequestOptions();

            var request = new ChatRequest(SocketClient, $"{tags}{command} {parameters}".Trim(), options);
            await request.SendAsync().ConfigureAwait(false);

            await _sentChatMessageEvent.InvokeAsync(command).ConfigureAwait(false);
        }
        public DiscordRpcApiClient(string clientId, string userAgent, string origin, RestClientProvider restClientProvider, WebSocketProvider webSocketProvider,
                                   RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializer serializer = null)
            : base(restClientProvider, userAgent, defaultRetryMode, serializer)
        {
            _connectionLock = new SemaphoreSlim(1, 1);
            _clientId       = clientId;
            _origin         = origin;

            _requests = new ConcurrentDictionary <Guid, RpcRequest>();

            _webSocketClient = webSocketProvider();
            //_webSocketClient.SetHeader("user-agent", DiscordConfig.UserAgent); (Causes issues in .Net 4.6+)
            _webSocketClient.SetHeader("origin", _origin);
            _webSocketClient.BinaryMessage += async(data, index, count) =>
            {
                using (var compressed = new MemoryStream(data, index + 2, count - 2))
                    using (var decompressed = new MemoryStream())
                    {
                        using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
                            zlib.CopyTo(decompressed);
                        decompressed.Position = 0;
                        using (var reader = new StreamReader(decompressed))
                            using (var jsonReader = new JsonTextReader(reader))
                            {
                                var msg = _serializer.Deserialize <API.Rpc.RpcFrame>(jsonReader);
                                await _receivedRpcEvent.InvokeAsync(msg.Cmd, msg.Event, msg.Data).ConfigureAwait(false);

                                if (msg.Nonce.IsSpecified && msg.Nonce.Value.HasValue)
                                {
                                    ProcessMessage(msg);
                                }
                            }
                    }
            };
            _webSocketClient.TextMessage += async text =>
            {
                using (var reader = new StringReader(text))
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        var msg = _serializer.Deserialize <API.Rpc.RpcFrame>(jsonReader);
                        await _receivedRpcEvent.InvokeAsync(msg.Cmd, msg.Event, msg.Data).ConfigureAwait(false);

                        if (msg.Nonce.IsSpecified && msg.Nonce.Value.HasValue)
                        {
                            ProcessMessage(msg);
                        }
                    }
            };
            _webSocketClient.Closed += async ex =>
            {
                await DisconnectAsync().ConfigureAwait(false);

                await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
            };
        }
Exemplo n.º 24
0
        public async void RunAsyncEvent()
        {
            var x1 = new AsyncEvent();

            x1.Subscribe(AddTask);
            var x2 = new AsyncEvent();

            x2.Subscribe(x1);
            await x2.InvokeAsync(this, new EventArgs()).ConfigureAwait(false);

            await x2.InvokeAsync(this, new EventArgs()).ConfigureAwait(false);

            Assert.Equal(2, _counter);
            x2.Unsubscribe(x1);
            await x2.InvokeAsync(this, new EventArgs()).ConfigureAwait(false);

            await x2.InvokeAsync(this, new EventArgs()).ConfigureAwait(false);

            Assert.Equal(2, _counter);
        }
Exemplo n.º 25
0
        //Udp
        public async Task SendDiscoveryAsync(uint ssrc)
        {
            byte[] packet = new byte[70];
            packet[0] = (byte)(ssrc >> 24);
            packet[1] = (byte)(ssrc >> 16);
            packet[2] = (byte)(ssrc >> 8);
            packet[3] = (byte)(ssrc >> 0);
            await SendAsync(packet, 0, 70).ConfigureAwait(false);

            await _sentDiscoveryEvent.InvokeAsync().ConfigureAwait(false);
        }
Exemplo n.º 26
0
        private async Task OnDocumentsRemovingAsync(ICollection <T> documents)
        {
            await InvalidateCacheAsync(documents).AnyContext();

            if (DocumentsRemoving != null)
            {
                await DocumentsRemoving.InvokeAsync(this, new DocumentsEventArgs <T>(documents, this)).AnyContext();
            }

            await OnDocumentsChangingAsync(ChangeType.Removed, documents).AnyContext();
        }
        private async Task SendGatewayInternalAsync(GatewayOpCode opCode, object payload, RequestOptions options)
        {
            CheckState();

            //TODO: Add ETF
            byte[] bytes = null;
            payload = new SocketFrame { Operation = (int)opCode, Payload = payload };
            if (payload != null)
                bytes = Encoding.UTF8.GetBytes(SerializeJson(payload));
            await RequestQueue.SendAsync(new WebSocketRequest(WebSocketClient, null, bytes, true, options)).ConfigureAwait(false);
            await _sentGatewayMessageEvent.InvokeAsync(opCode).ConfigureAwait(false);
        }
Exemplo n.º 28
0
        public async void AsyncEventDispatches()
        {
            var counter = 0;
            var ev      = new AsyncEvent();

            Task MyMethod()
            {
                counter++;
                return(Task.CompletedTask);
            }

            ev.Subscribe(MyMethod);
            await ev.InvokeAsync(this, new EventArgs());

            Assert.Equal(1, counter);

            ev.Unsubscribe(MyMethod);
            await ev.InvokeAsync(this, new EventArgs());

            Assert.Equal(1, counter);
        }
Exemplo n.º 29
0
 public async Task LogAsync(LogSeverity severity, string source, string message, Exception ex = null)
 {
     if (severity <= Level)
     {
         await _messageEvent.InvokeAsync(new LogMessage(severity, source, message, ex)).ConfigureAwait(false);
     }
 }
Exemplo n.º 30
0
        internal DiscordVoiceAPIClient(ulong guildId, WebSocketProvider webSocketProvider, JsonSerializer serializer = null)
        {
            GuildId         = guildId;
            _connectionLock = new SemaphoreSlim(1, 1);
            _udp            = new UdpClient(new IPEndPoint(IPAddress.Any, 0));

            _webSocketClient = webSocketProvider();
            //_gatewayClient.SetHeader("user-agent", DiscordConfig.UserAgent); (Causes issues in .Net 4.6+)
            _webSocketClient.BinaryMessage += async(data, index, count) =>
            {
                using (var compressed = new MemoryStream(data, index + 2, count - 2))
                    using (var decompressed = new MemoryStream())
                    {
                        using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
                            zlib.CopyTo(decompressed);
                        decompressed.Position = 0;
                        using (var reader = new StreamReader(decompressed))
                        {
                            var msg = JsonConvert.DeserializeObject <WebSocketMessage>(reader.ReadToEnd());
                            await _receivedEvent.InvokeAsync((VoiceOpCode)msg.Operation, msg.Payload).ConfigureAwait(false);
                        }
                    }
            };
            _webSocketClient.TextMessage += async text =>
            {
                var msg = JsonConvert.DeserializeObject <WebSocketMessage>(text);
                await _receivedEvent.InvokeAsync((VoiceOpCode)msg.Operation, msg.Payload).ConfigureAwait(false);
            };
            _webSocketClient.Closed += async ex =>
            {
                await DisconnectAsync().ConfigureAwait(false);

                await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
            };

            _serializer = serializer ?? new JsonSerializer {
                ContractResolver = new DiscordContractResolver()
            };
        }