Skip to content

Commit

Permalink
Fix issues with #984, remove extraneous whitespace (#1051)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
FiniteReality authored and foxbot committed May 4, 2018
1 parent 7cfed7f commit bb4bb13
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 34 deletions.
72 changes: 39 additions & 33 deletions src/Discord.Net.WebSocket/DiscordSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds;
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();
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
=> State.PrivateChannels.Select(x => x as SocketGroupChannel).Where(x => x != null).ToImmutableArray();
public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection();

Expand All @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -136,7 +136,7 @@ internal override void Dispose(bool disposing)
ApiClient.Dispose();
}
}

internal override async Task OnLoginAsync(TokenType tokenType, string token)
{
if (_parentClient == null)
Expand All @@ -154,11 +154,11 @@ internal override async Task OnLogoutAsync()
_voiceRegions = ImmutableDictionary.Create<string, RestVoiceRegion>();
}

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)
Expand All @@ -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)
{
Expand Down Expand Up @@ -230,22 +230,22 @@ private async Task OnDisconnectingAsync(Exception ex)
}

/// <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));

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

/// <inheritdoc />
public override SocketChannel GetChannel(ulong id)
public override SocketChannel GetChannel(ulong id)
=> State.GetChannel(id);

/// <inheritdoc />
public override SocketUser GetUser(ulong id)
public override SocketUser GetUser(ulong id)
=> State.GetUser(id);
/// <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);
internal SocketGlobalUser GetOrCreateUser(ClientState state, Discord.API.User model)
{
Expand All @@ -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);

/// <inheritdoc />
Expand Down Expand Up @@ -340,7 +340,7 @@ public override async Task SetActivityAsync(IActivity activity)
Activity = activity;
await SendStatusAsync().ConfigureAwait(false);
}

private async Task SendStatusAsync()
{
if (CurrentUser == null)
Expand Down Expand Up @@ -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)
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
});
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -1466,21 +1466,27 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty

var data = (payload as JToken).ToObject<VoiceServerUpdateEvent>(_serializer);
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);

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;
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class SocketVoiceServer
public string Endpoint { 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;
Endpoint = endpoint;
Expand Down

0 comments on commit bb4bb13

Please sign in to comment.