Browse Source

Fix issues with #984, remove extraneous whitespace (#1051)

- Removed unnecessary parameter in SocketVoiceServer

- Moved SocketVoiceServer into Entities/Voice

- Fixed a bug where trying to download the cached guild would throw

- Fixed a potential bug where Discord might not give us a port when
  connecting to voice
tags/2.0
Finite Reality Christopher F 7 years ago
parent
commit
bb4bb13846
2 changed files with 40 additions and 34 deletions
  1. +39
    -33
      src/Discord.Net.WebSocket/DiscordSocketClient.cs
  2. +1
    -1
      src/Discord.Net.WebSocket/Entities/Voice/SocketVoiceServer.cs

+ 39
- 33
src/Discord.Net.WebSocket/DiscordSocketClient.cs View File

@@ -62,9 +62,9 @@ namespace Discord.WebSocket
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient; internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds; public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds;
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels; public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels;
public IReadOnlyCollection<SocketDMChannel> DMChannels
public IReadOnlyCollection<SocketDMChannel> DMChannels
=> State.PrivateChannels.Select(x => x as SocketDMChannel).Where(x => x != null).ToImmutableArray(); => State.PrivateChannels.Select(x => x as SocketDMChannel).Where(x => x != null).ToImmutableArray();
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
=> State.PrivateChannels.Select(x => x as SocketGroupChannel).Where(x => x != null).ToImmutableArray(); => State.PrivateChannels.Select(x => x as SocketGroupChannel).Where(x => x != null).ToImmutableArray();
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection(); public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection();


@@ -89,11 +89,11 @@ namespace Discord.WebSocket


_stateLock = new SemaphoreSlim(1, 1); _stateLock = new SemaphoreSlim(1, 1);
_gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : $"Shard #{ShardId}"); _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); OnConnectingAsync, OnDisconnectingAsync, x => ApiClient.Disconnected += x);
_connection.Connected += () => TimedInvokeAsync(_connectedEvent, nameof(Connected)); _connection.Connected += () => TimedInvokeAsync(_connectedEvent, nameof(Connected));
_connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex); _connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex);
_nextAudioId = 1; _nextAudioId = 1;
_connectionGroupLock = groupLock; _connectionGroupLock = groupLock;
_parentClient = parentClient; _parentClient = parentClient;
@@ -104,7 +104,7 @@ namespace Discord.WebSocket
_gatewayLogger.WarningAsync("Serializer Error", e.ErrorContext.Error).GetAwaiter().GetResult(); _gatewayLogger.WarningAsync("Serializer Error", e.ErrorContext.Error).GetAwaiter().GetResult();
e.ErrorContext.Handled = true; e.ErrorContext.Handled = true;
}; };
ApiClient.SentGatewayMessage += async opCode => await _gatewayLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false); ApiClient.SentGatewayMessage += async opCode => await _gatewayLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
ApiClient.ReceivedGatewayEvent += ProcessMessageAsync; ApiClient.ReceivedGatewayEvent += ProcessMessageAsync;


@@ -136,7 +136,7 @@ namespace Discord.WebSocket
ApiClient.Dispose(); ApiClient.Dispose();
} }
} }
internal override async Task OnLoginAsync(TokenType tokenType, string token) internal override async Task OnLoginAsync(TokenType tokenType, string token)
{ {
if (_parentClient == null) if (_parentClient == null)
@@ -154,11 +154,11 @@ namespace Discord.WebSocket
_voiceRegions = ImmutableDictionary.Create<string, RestVoiceRegion>(); _voiceRegions = ImmutableDictionary.Create<string, RestVoiceRegion>();
} }


public override async Task StartAsync()
public override async Task StartAsync()
=> await _connection.StartAsync().ConfigureAwait(false); => await _connection.StartAsync().ConfigureAwait(false);
public override async Task StopAsync()
public override async Task StopAsync()
=> await _connection.StopAsync().ConfigureAwait(false); => await _connection.StopAsync().ConfigureAwait(false);
private async Task OnConnectingAsync() private async Task OnConnectingAsync()
{ {
if (_connectionGroupLock != null) if (_connectionGroupLock != null)
@@ -181,11 +181,11 @@ namespace Discord.WebSocket


//Wait for READY //Wait for READY
await _connection.WaitAsync().ConfigureAwait(false); await _connection.WaitAsync().ConfigureAwait(false);
await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false); await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false);
await SendStatusAsync().ConfigureAwait(false); await SendStatusAsync().ConfigureAwait(false);
} }
finally
finally
{ {
if (_connectionGroupLock != null) if (_connectionGroupLock != null)
{ {
@@ -230,22 +230,22 @@ namespace Discord.WebSocket
} }


/// <inheritdoc /> /// <inheritdoc />
public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
=> _applicationInfo ?? (_applicationInfo = await ClientHelper.GetApplicationInfoAsync(this, options ?? RequestOptions.Default).ConfigureAwait(false)); => _applicationInfo ?? (_applicationInfo = await ClientHelper.GetApplicationInfoAsync(this, options ?? RequestOptions.Default).ConfigureAwait(false));


/// <inheritdoc /> /// <inheritdoc />
public override SocketGuild GetGuild(ulong id)
=> State.GetGuild(id);
public override SocketGuild GetGuild(ulong id)
=> State.GetGuild(id);


/// <inheritdoc /> /// <inheritdoc />
public override SocketChannel GetChannel(ulong id)
public override SocketChannel GetChannel(ulong id)
=> State.GetChannel(id); => State.GetChannel(id);
/// <inheritdoc /> /// <inheritdoc />
public override SocketUser GetUser(ulong id)
public override SocketUser GetUser(ulong id)
=> State.GetUser(id); => State.GetUser(id);
/// <inheritdoc /> /// <inheritdoc />
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); => State.Users.FirstOrDefault(x => x.Discriminator == discriminator && x.Username == username);
internal SocketGlobalUser GetOrCreateUser(ClientState state, Discord.API.User model) internal SocketGlobalUser GetOrCreateUser(ClientState state, Discord.API.User model)
{ {
@@ -266,7 +266,7 @@ namespace Discord.WebSocket
return user; return user;
}); });
} }
internal void RemoveUser(ulong id)
internal void RemoveUser(ulong id)
=> State.RemoveUser(id); => State.RemoveUser(id);


/// <inheritdoc /> /// <inheritdoc />
@@ -340,7 +340,7 @@ namespace Discord.WebSocket
Activity = activity; Activity = activity;
await SendStatusAsync().ConfigureAwait(false); await SendStatusAsync().ConfigureAwait(false);
} }
private async Task SendStatusAsync() private async Task SendStatusAsync()
{ {
if (CurrentUser == null) if (CurrentUser == null)
@@ -374,7 +374,7 @@ namespace Discord.WebSocket
if (seq != null) if (seq != null)
_lastSeq = seq.Value; _lastSeq = seq.Value;
_lastMessageTime = Environment.TickCount; _lastMessageTime = Environment.TickCount;
try try
{ {
switch (opCode) switch (opCode)
@@ -390,7 +390,7 @@ namespace Discord.WebSocket
case GatewayOpCode.Heartbeat: case GatewayOpCode.Heartbeat:
{ {
await _gatewayLogger.DebugAsync("Received Heartbeat").ConfigureAwait(false); await _gatewayLogger.DebugAsync("Received Heartbeat").ConfigureAwait(false);
await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false); await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false);
} }
break; break;
@@ -415,7 +415,7 @@ namespace Discord.WebSocket


_sessionId = null; _sessionId = null;
_lastSeq = 0; _lastSeq = 0;
await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards).ConfigureAwait(false); await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards).ConfigureAwait(false);
} }
break; break;
@@ -475,7 +475,7 @@ namespace Discord.WebSocket
} }
else if (_connection.CancelToken.IsCancellationRequested) else if (_connection.CancelToken.IsCancellationRequested)
return; return;
await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false); await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false);
await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false); await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false);
}); });
@@ -514,7 +514,7 @@ namespace Discord.WebSocket
if (guild != null) if (guild != null)
{ {
guild.Update(State, data); guild.Update(State, data);
if (_unavailableGuildCount != 0) if (_unavailableGuildCount != 0)
_unavailableGuildCount--; _unavailableGuildCount--;
await GuildAvailableAsync(guild).ConfigureAwait(false); await GuildAvailableAsync(guild).ConfigureAwait(false);
@@ -1025,7 +1025,7 @@ namespace Discord.WebSocket


SocketUser user = guild.GetUser(data.User.Id); SocketUser user = guild.GetUser(data.User.Id);
if (user == null) 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); await TimedInvokeAsync(_userBannedEvent, nameof(UserBanned), user, guild).ConfigureAwait(false);
} }
else else
@@ -1325,7 +1325,7 @@ namespace Discord.WebSocket
await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false); await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false);
} }
} }
var before = user.Clone(); var before = user.Clone();
user.Update(State, data, true); user.Update(State, data, true);
await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), before, user).ConfigureAwait(false); await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), before, user).ConfigureAwait(false);
@@ -1466,21 +1466,27 @@ namespace Discord.WebSocket


var data = (payload as JToken).ToObject<VoiceServerUpdateEvent>(_serializer); var data = (payload as JToken).ToObject<VoiceServerUpdateEvent>(_serializer);
var guild = State.GetGuild(data.GuildId); var guild = State.GetGuild(data.GuildId);
var cacheable = new Cacheable<IGuild, ulong>(guild, data.GuildId, guild != null,
async () => await ApiClient.GetGuildAsync(data.GuildId).ConfigureAwait(false) as IGuild);
var isCached = guild != null;
var cachedGuild = new Cacheable<IGuild, ulong>(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); 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); var _ = guild.FinishConnectAudio(endpoint, data.Token).ConfigureAwait(false);
} }
else else
{ {
await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false); await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
return;
} }


} }


src/Discord.Net.WebSocket/SocketVoiceServer.cs → src/Discord.Net.WebSocket/Entities/Voice/SocketVoiceServer.cs View File

@@ -9,7 +9,7 @@ namespace Discord.WebSocket
public string Endpoint { get; private set; } public string Endpoint { get; private set; }
public string Token { get; private set; } public string Token { get; private set; }


internal SocketVoiceServer(Cacheable<IGuild, ulong> guild, ulong guildId, string endpoint, string token)
internal SocketVoiceServer(Cacheable<IGuild, ulong> guild, string endpoint, string token)
{ {
Guild = guild; Guild = guild;
Endpoint = endpoint; Endpoint = endpoint;

Loading…
Cancel
Save