From 84ff89c6d6e33df91c0c4fc81106cc74d4d40b87 Mon Sep 17 00:00:00 2001 From: Radka Janek Date: Sun, 3 Sep 2017 17:01:02 +0200 Subject: [PATCH 1/2] Renamed private events to fit their actual purpose. --- src/Discord.Net.Rpc/DiscordRpcClient.cs | 14 +++---- .../ConnectionManager.cs | 30 ++++++------- .../DiscordSocketClient.cs | 42 +++++++++---------- 3 files changed, 43 insertions(+), 43 deletions(-) diff --git a/src/Discord.Net.Rpc/DiscordRpcClient.cs b/src/Discord.Net.Rpc/DiscordRpcClient.cs index 9c77fc919..b1bba17b7 100644 --- a/src/Discord.Net.Rpc/DiscordRpcClient.cs +++ b/src/Discord.Net.Rpc/DiscordRpcClient.cs @@ -29,7 +29,7 @@ namespace Discord.Rpc public RestApplication ApplicationInfo { get; private set; } /// Creates a new RPC discord client. - public DiscordRpcClient(string clientId, string origin) + public DiscordRpcClient(string clientId, string origin) : this(clientId, origin, new DiscordRpcConfig()) { } /// Creates a new RPC discord client. public DiscordRpcClient(string clientId, string origin, DiscordRpcConfig config) @@ -38,8 +38,8 @@ namespace Discord.Rpc _stateLock = new SemaphoreSlim(1, 1); _authorizeLock = new SemaphoreSlim(1, 1); _rpcLogger = LogManager.CreateLogger("RPC"); - _connection = new ConnectionManager(_stateLock, _rpcLogger, config.ConnectionTimeout, - OnConnectingAsync, OnDisconnectingAsync, x => ApiClient.Disconnected += x); + _connection = new ConnectionManager(_stateLock, _rpcLogger, config.ConnectionTimeout, + ConnectAsync, DisconnectAsync, x => ApiClient.Disconnected += x); _connection.Connected += () => _connectedEvent.InvokeAsync(); _connection.Disconnected += (ex, recon) => _disconnectedEvent.InvokeAsync(ex); @@ -49,7 +49,7 @@ namespace Discord.Rpc _rpcLogger.WarningAsync(e.ErrorContext.Error).GetAwaiter().GetResult(); e.ErrorContext.Handled = true; }; - + ApiClient.SentRpcMessage += async opCode => await _rpcLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false); ApiClient.ReceivedRpcEvent += ProcessMessageAsync; } @@ -68,14 +68,14 @@ namespace Discord.Rpc public Task StartAsync() => _connection.StartAsync(); public Task StopAsync() => _connection.StopAsync(); - private async Task OnConnectingAsync() + private async Task ConnectAsync() { await _rpcLogger.DebugAsync("Connecting ApiClient").ConfigureAwait(false); await ApiClient.ConnectAsync().ConfigureAwait(false); await _connection.WaitAsync().ConfigureAwait(false); } - private async Task OnDisconnectingAsync(Exception ex) + private async Task DisconnectAsync(Exception ex) { await _rpcLogger.DebugAsync("Disconnecting ApiClient").ConfigureAwait(false); await ApiClient.DisconnectAsync().ConfigureAwait(false); @@ -313,7 +313,7 @@ namespace Discord.Rpc ApplicationInfo = RestApplication.Create(this, response.Application); Scopes = response.Scopes; TokenExpiresAt = response.Expires; - + var __ = _connection.CompleteAsync(); await _rpcLogger.InfoAsync("Ready").ConfigureAwait(false); } diff --git a/src/Discord.Net.WebSocket/ConnectionManager.cs b/src/Discord.Net.WebSocket/ConnectionManager.cs index decae4163..0a222e491 100644 --- a/src/Discord.Net.WebSocket/ConnectionManager.cs +++ b/src/Discord.Net.WebSocket/ConnectionManager.cs @@ -16,8 +16,8 @@ namespace Discord private readonly SemaphoreSlim _stateLock; private readonly Logger _logger; private readonly int _connectionTimeout; - private readonly Func _onConnecting; - private readonly Func _onDisconnecting; + private readonly Func _connect; + private readonly Func _disconnect; private TaskCompletionSource _connectionPromise, _readyPromise; private CancellationTokenSource _combinedCancelToken, _reconnectCancelToken, _connectionCancelToken; @@ -26,14 +26,14 @@ namespace Discord public ConnectionState State { get; private set; } public CancellationToken CancelToken { get; private set; } - internal ConnectionManager(SemaphoreSlim stateLock, Logger logger, int connectionTimeout, - Func onConnecting, Func onDisconnecting, Action> clientDisconnectHandler) + internal ConnectionManager(SemaphoreSlim stateLock, Logger logger, int connectionTimeout, + Func connect, Func disconnect, Action> clientDisconnectHandler) { _stateLock = stateLock; _logger = logger; _connectionTimeout = connectionTimeout; - _onConnecting = onConnecting; - _onDisconnecting = onDisconnecting; + _connect = connect; + _disconnect = disconnect; clientDisconnectHandler(ex => { @@ -67,16 +67,16 @@ namespace Discord try { await ConnectAsync(reconnectCancelToken).ConfigureAwait(false); - nextReconnectDelay = 1000; //Reset delay + nextReconnectDelay = 1000; //Reset delay await _connectionPromise.Task.ConfigureAwait(false); } - catch (OperationCanceledException ex) - { + catch (OperationCanceledException ex) + { Cancel(); //In case this exception didn't come from another Error call await DisconnectAsync(ex, !reconnectCancelToken.IsCancellationRequested).ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) + { Error(ex); //In case this exception didn't come from another Error call if (!reconnectCancelToken.IsCancellationRequested) { @@ -120,7 +120,7 @@ namespace Discord _connectionPromise = new TaskCompletionSource(); State = ConnectionState.Connecting; await _logger.InfoAsync("Connecting").ConfigureAwait(false); - + try { var readyPromise = new TaskCompletionSource(); @@ -138,7 +138,7 @@ namespace Discord catch (OperationCanceledException) { } }); - await _onConnecting().ConfigureAwait(false); + await _connect().ConfigureAwait(false); await _logger.InfoAsync("Connected").ConfigureAwait(false); State = ConnectionState.Connected; @@ -157,7 +157,7 @@ namespace Discord State = ConnectionState.Disconnecting; await _logger.InfoAsync("Disconnecting").ConfigureAwait(false); - await _onDisconnecting(ex).ConfigureAwait(false); + await _disconnect(ex).ConfigureAwait(false); await _logger.InfoAsync("Disconnected").ConfigureAwait(false); State = ConnectionState.Disconnected; @@ -207,4 +207,4 @@ namespace Discord } } } -} \ No newline at end of file +} diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index 5256e0efd..dcd61a52f 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -63,9 +63,9 @@ namespace Discord.WebSocket public new SocketSelfUser CurrentUser { get => base.CurrentUser as SocketSelfUser; private set => base.CurrentUser = value; } public IReadOnlyCollection Guilds => State.Guilds; public IReadOnlyCollection PrivateChannels => State.PrivateChannels; - public IReadOnlyCollection DMChannels + public IReadOnlyCollection DMChannels => State.PrivateChannels.Select(x => x as SocketDMChannel).Where(x => x != null).ToImmutableArray(); - public IReadOnlyCollection GroupChannels + public IReadOnlyCollection GroupChannels => State.PrivateChannels.Select(x => x as SocketGroupChannel).Where(x => x != null).ToImmutableArray(); public IReadOnlyCollection VoiceRegions => _voiceRegions.ToReadOnlyCollection(); @@ -90,11 +90,11 @@ namespace Discord.WebSocket _stateLock = new SemaphoreSlim(1, 1); _gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : $"Shard #{ShardId}"); - _connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout, - OnConnectingAsync, OnDisconnectingAsync, x => ApiClient.Disconnected += x); + _connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout, + ConnectAsync, DisconnectAsync, x => ApiClient.Disconnected += x); _connection.Connected += () => TimedInvokeAsync(_connectedEvent, nameof(Connected)); _connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex); - + _nextAudioId = 1; _connectionGroupLock = groupLock; _parentClient = parentClient; @@ -105,7 +105,7 @@ namespace Discord.WebSocket _gatewayLogger.WarningAsync("Serializer Error", e.ErrorContext.Error).GetAwaiter().GetResult(); e.ErrorContext.Handled = true; }; - + ApiClient.SentGatewayMessage += async opCode => await _gatewayLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false); ApiClient.ReceivedGatewayEvent += ProcessMessageAsync; @@ -137,7 +137,7 @@ namespace Discord.WebSocket ApiClient.Dispose(); } } - + internal override async Task OnLoginAsync(TokenType tokenType, string token) { if (_parentClient == null) @@ -155,12 +155,12 @@ namespace Discord.WebSocket _voiceRegions = ImmutableDictionary.Create(); } - public async Task StartAsync() + public async Task StartAsync() => await _connection.StartAsync().ConfigureAwait(false); - public async Task StopAsync() + public async Task StopAsync() => await _connection.StopAsync().ConfigureAwait(false); - - private async Task OnConnectingAsync() + + private async Task ConnectAsync() { if (_connectionGroupLock != null) await _connectionGroupLock.WaitAsync(_connection.CancelToken).ConfigureAwait(false); @@ -182,11 +182,11 @@ namespace Discord.WebSocket //Wait for READY await _connection.WaitAsync().ConfigureAwait(false); - + await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false); await SendStatusAsync().ConfigureAwait(false); } - finally + finally { if (_connectionGroupLock != null) { @@ -195,7 +195,7 @@ namespace Discord.WebSocket } } } - private async Task OnDisconnectingAsync(Exception ex) + private async Task DisconnectAsync(Exception ex) { await _gatewayLogger.DebugAsync("Disconnecting ApiClient").ConfigureAwait(false); @@ -232,7 +232,7 @@ namespace Discord.WebSocket /// public async Task GetApplicationInfoAsync() - { + { return _applicationInfo ?? (_applicationInfo = await ClientHelper.GetApplicationInfoAsync(this, new RequestOptions())); } @@ -391,7 +391,7 @@ namespace Discord.WebSocket if (seq != null) _lastSeq = seq.Value; _lastMessageTime = Environment.TickCount; - + try { switch (opCode) @@ -407,7 +407,7 @@ namespace Discord.WebSocket case GatewayOpCode.Heartbeat: { await _gatewayLogger.DebugAsync("Received Heartbeat").ConfigureAwait(false); - + await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false); } break; @@ -498,7 +498,7 @@ namespace Discord.WebSocket } else if (_connection.CancelToken.IsCancellationRequested) return; - + await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false); await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false); }); @@ -537,7 +537,7 @@ namespace Discord.WebSocket if (guild != null) { guild.Update(State, data); - + if (_unavailableGuildCount != 0) _unavailableGuildCount--; await GuildAvailableAsync(guild).ConfigureAwait(false); @@ -1050,7 +1050,7 @@ namespace Discord.WebSocket SocketUser user = guild.GetUser(data.User.Id); if (user == null) - user = SocketUnknownUser.Create(this, State, data.User); + user = SocketUnknownUser.Create(this, State, data.User); await TimedInvokeAsync(_userBannedEvent, nameof(UserBanned), user, guild).ConfigureAwait(false); } else @@ -1348,7 +1348,7 @@ namespace Discord.WebSocket await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false); } } - + var before = user.Clone(); user.Update(State, data, true); await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), before, user).ConfigureAwait(false); From 5fdfee89ce0f55e55fd68e7db22642740a2d473b Mon Sep 17 00:00:00 2001 From: Radka Janek Date: Sun, 3 Sep 2017 17:35:27 +0200 Subject: [PATCH 2/2] 'Added connection event `Connecting`' --- src/Discord.Net.Rpc/DiscordRpcClient.Events.cs | 6 ++++++ src/Discord.Net.Rpc/DiscordRpcClient.cs | 1 + src/Discord.Net.WebSocket/ConnectionManager.cs | 4 ++++ src/Discord.Net.WebSocket/DiscordSocketClient.Events.cs | 6 ++++++ src/Discord.Net.WebSocket/DiscordSocketClient.cs | 1 + 5 files changed, 18 insertions(+) diff --git a/src/Discord.Net.Rpc/DiscordRpcClient.Events.cs b/src/Discord.Net.Rpc/DiscordRpcClient.Events.cs index 2a9ae21bf..f58f03c52 100644 --- a/src/Discord.Net.Rpc/DiscordRpcClient.Events.cs +++ b/src/Discord.Net.Rpc/DiscordRpcClient.Events.cs @@ -6,6 +6,12 @@ namespace Discord.Rpc public partial class DiscordRpcClient { //General + public event Func Connecting + { + add { _connectingEvent.Add(value); } + remove { _connectingEvent.Remove(value); } + } + private readonly AsyncEvent> _connectingEvent = new AsyncEvent>(); public event Func Connected { add { _connectedEvent.Add(value); } diff --git a/src/Discord.Net.Rpc/DiscordRpcClient.cs b/src/Discord.Net.Rpc/DiscordRpcClient.cs index b1bba17b7..19d7e9dfc 100644 --- a/src/Discord.Net.Rpc/DiscordRpcClient.cs +++ b/src/Discord.Net.Rpc/DiscordRpcClient.cs @@ -40,6 +40,7 @@ namespace Discord.Rpc _rpcLogger = LogManager.CreateLogger("RPC"); _connection = new ConnectionManager(_stateLock, _rpcLogger, config.ConnectionTimeout, ConnectAsync, DisconnectAsync, x => ApiClient.Disconnected += x); + _connection.Connecting += () => _connectingEvent.InvokeAsync(); _connection.Connected += () => _connectedEvent.InvokeAsync(); _connection.Disconnected += (ex, recon) => _disconnectedEvent.InvokeAsync(ex); diff --git a/src/Discord.Net.WebSocket/ConnectionManager.cs b/src/Discord.Net.WebSocket/ConnectionManager.cs index 0a222e491..d7682a2af 100644 --- a/src/Discord.Net.WebSocket/ConnectionManager.cs +++ b/src/Discord.Net.WebSocket/ConnectionManager.cs @@ -8,6 +8,8 @@ namespace Discord { internal class ConnectionManager { + public event Func Connecting { add { _connectingEvent.Add(value); } remove { _connectingEvent.Remove(value); } } + private readonly AsyncEvent> _connectingEvent = new AsyncEvent>(); public event Func Connected { add { _connectedEvent.Add(value); } remove { _connectedEvent.Remove(value); } } private readonly AsyncEvent> _connectedEvent = new AsyncEvent>(); public event Func Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } } @@ -123,6 +125,8 @@ namespace Discord try { + await _connectingEvent.InvokeAsync().ConfigureAwait(false); + var readyPromise = new TaskCompletionSource(); _readyPromise = readyPromise; diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.Events.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.Events.cs index fb155e535..cabdf98ee 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.Events.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.Events.cs @@ -7,6 +7,12 @@ namespace Discord.WebSocket public partial class DiscordSocketClient { //General + public event Func Connecting + { + add { _connectingEvent.Add(value); } + remove { _connectingEvent.Remove(value); } + } + private readonly AsyncEvent> _connectingEvent = new AsyncEvent>(); public event Func Connected { add { _connectedEvent.Add(value); } diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index dcd61a52f..89502eb03 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -92,6 +92,7 @@ namespace Discord.WebSocket _gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : $"Shard #{ShardId}"); _connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout, ConnectAsync, DisconnectAsync, x => ApiClient.Disconnected += x); + _connection.Connecting += () => TimedInvokeAsync(_connectingEvent, nameof(Connecting)); _connection.Connected += () => TimedInvokeAsync(_connectedEvent, nameof(Connected)); _connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex);