diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index 95925291bd..72b0b022bf 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -62,9 +62,9 @@ public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient; public override IReadOnlyCollection Guilds => State.Guilds; public override 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 override IReadOnlyCollection VoiceRegions => _voiceRegions.ToReadOnlyCollection(); @@ -89,11 +89,11 @@ private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClie _stateLock = new SemaphoreSlim(1, 1); _gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : $"Shard #{ShardId}"); - _connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout, + _connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout, OnConnectingAsync, OnDisconnectingAsync, 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; @@ -104,7 +104,7 @@ private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClie _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; @@ -136,7 +136,7 @@ internal override void Dispose(bool disposing) ApiClient.Dispose(); } } - + internal override async Task OnLoginAsync(TokenType tokenType, string token) { if (_parentClient == null) @@ -154,11 +154,11 @@ internal override async Task OnLogoutAsync() _voiceRegions = ImmutableDictionary.Create(); } - public override async Task StartAsync() + public override async Task StartAsync() => await _connection.StartAsync().ConfigureAwait(false); - public override async Task StopAsync() + public override async Task StopAsync() => await _connection.StopAsync().ConfigureAwait(false); - + private async Task OnConnectingAsync() { if (_connectionGroupLock != null) @@ -181,11 +181,11 @@ private async Task OnConnectingAsync() //Wait for READY await _connection.WaitAsync().ConfigureAwait(false); - + await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false); await SendStatusAsync().ConfigureAwait(false); } - finally + finally { if (_connectionGroupLock != null) { @@ -230,22 +230,22 @@ private async Task OnDisconnectingAsync(Exception ex) } /// - public override async Task GetApplicationInfoAsync(RequestOptions options = null) + public override async Task GetApplicationInfoAsync(RequestOptions options = null) => _applicationInfo ?? (_applicationInfo = await ClientHelper.GetApplicationInfoAsync(this, options ?? RequestOptions.Default).ConfigureAwait(false)); /// - public override SocketGuild GetGuild(ulong id) - => State.GetGuild(id); + public override SocketGuild GetGuild(ulong id) + => State.GetGuild(id); /// - public override SocketChannel GetChannel(ulong id) + public override SocketChannel GetChannel(ulong id) => State.GetChannel(id); - + /// - public override SocketUser GetUser(ulong id) + public override SocketUser GetUser(ulong id) => State.GetUser(id); /// - public override SocketUser GetUser(string username, string discriminator) + public override SocketUser GetUser(string username, string discriminator) => State.Users.FirstOrDefault(x => x.Discriminator == discriminator && x.Username == username); internal SocketGlobalUser GetOrCreateUser(ClientState state, Discord.API.User model) { @@ -266,7 +266,7 @@ internal SocketGlobalUser GetOrCreateSelfUser(ClientState state, Discord.API.Use return user; }); } - internal void RemoveUser(ulong id) + internal void RemoveUser(ulong id) => State.RemoveUser(id); /// @@ -340,7 +340,7 @@ public override async Task SetActivityAsync(IActivity activity) Activity = activity; await SendStatusAsync().ConfigureAwait(false); } - + private async Task SendStatusAsync() { if (CurrentUser == null) @@ -374,7 +374,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty if (seq != null) _lastSeq = seq.Value; _lastMessageTime = Environment.TickCount; - + try { switch (opCode) @@ -390,7 +390,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty case GatewayOpCode.Heartbeat: { await _gatewayLogger.DebugAsync("Received Heartbeat").ConfigureAwait(false); - + await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false); } break; @@ -415,7 +415,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty _sessionId = null; _lastSeq = 0; - + await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards).ConfigureAwait(false); } break; @@ -475,7 +475,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty } else if (_connection.CancelToken.IsCancellationRequested) return; - + await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false); await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false); }); @@ -514,7 +514,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty if (guild != null) { guild.Update(State, data); - + if (_unavailableGuildCount != 0) _unavailableGuildCount--; await GuildAvailableAsync(guild).ConfigureAwait(false); @@ -1025,7 +1025,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty 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 @@ -1325,7 +1325,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty 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); @@ -1466,21 +1466,27 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty var data = (payload as JToken).ToObject(_serializer); var guild = State.GetGuild(data.GuildId); - var cacheable = new Cacheable(guild, data.GuildId, guild != null, - async () => await ApiClient.GetGuildAsync(data.GuildId).ConfigureAwait(false) as IGuild); + var isCached = guild != null; + var cachedGuild = new Cacheable(guild, data.GuildId, isCached, + () => Task.FromResult(State.GetGuild(data.GuildId) as IGuild)); - var voiceServer = new SocketVoiceServer(cacheable, data.GuildId, data.Endpoint, data.Token); + var voiceServer = new SocketVoiceServer(cachedGuild, data.Endpoint, data.Token); await TimedInvokeAsync(_voiceServerUpdatedEvent, nameof(UserVoiceStateUpdated), voiceServer).ConfigureAwait(false); - if (guild != null) + if (isCached) { - string endpoint = data.Endpoint.Substring(0, data.Endpoint.LastIndexOf(':')); + var endpoint = data.Endpoint; + + //Only strip out the port if the endpoint contains it + var portBegin = endpoint.LastIndexOf(':'); + if (portBegin > 0) + endpoint = endpoint.Substring(0, portBegin); + var _ = guild.FinishConnectAudio(endpoint, data.Token).ConfigureAwait(false); } else { await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false); - return; } } diff --git a/src/Discord.Net.WebSocket/SocketVoiceServer.cs b/src/Discord.Net.WebSocket/Entities/Voice/SocketVoiceServer.cs similarity index 92% rename from src/Discord.Net.WebSocket/SocketVoiceServer.cs rename to src/Discord.Net.WebSocket/Entities/Voice/SocketVoiceServer.cs index 9ab6afd3f6..57abf1d03d 100644 --- a/src/Discord.Net.WebSocket/SocketVoiceServer.cs +++ b/src/Discord.Net.WebSocket/Entities/Voice/SocketVoiceServer.cs @@ -9,7 +9,7 @@ public class SocketVoiceServer public string Endpoint { get; private set; } public string Token { get; private set; } - internal SocketVoiceServer(Cacheable guild, ulong guildId, string endpoint, string token) + internal SocketVoiceServer(Cacheable guild, string endpoint, string token) { Guild = guild; Endpoint = endpoint;