Skip to content

Commit

Permalink
Update for latest nightly
Browse files Browse the repository at this point in the history
  • Loading branch information
NycroV committed Aug 13, 2024
1 parent 0e85c72 commit fa61e65
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 122 deletions.
93 changes: 0 additions & 93 deletions src/Lavalink4NET.DSharpPlus.Nightly/DSharpPlusUtilities.cs

This file was deleted.

60 changes: 33 additions & 27 deletions src/Lavalink4NET.DSharpPlus.Nightly/DiscordClientWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,38 @@ namespace Lavalink4NET.DSharpPlus;
using System.Threading;
using System.Threading.Tasks;
using global::DSharpPlus;
using global::DSharpPlus.AsyncEvents;
using global::DSharpPlus.Clients;
using global::DSharpPlus.Entities;
using global::DSharpPlus.EventArgs;
using global::DSharpPlus.Exceptions;
using global::DSharpPlus.Net.Abstractions;
using Lavalink4NET.Clients;
using L4N = Clients.Events;
using Lavalink4NET = Clients.Events;
using Lavalink4NET.Events;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Reflection;

/// <summary>
/// Wraps a <see cref="DiscordClient"/> instance.
/// </summary>
public sealed class DiscordClientWrapper : IDiscordClientWrapper
{
/// <inheritdoc/>
public event AsyncEventHandler<L4N.VoiceServerUpdatedEventArgs>? VoiceServerUpdated;
public event AsyncEventHandler<Lavalink4NET.VoiceServerUpdatedEventArgs>? VoiceServerUpdated;

/// <inheritdoc/>
public event AsyncEventHandler<L4N.VoiceStateUpdatedEventArgs>? VoiceStateUpdated;
public event AsyncEventHandler<Lavalink4NET.VoiceStateUpdatedEventArgs>? VoiceStateUpdated;

private readonly DiscordClient _client; // sharded clients are now also managed by the same DiscordClient type
private readonly DiscordClient _client;
private readonly ILogger<DiscordClientWrapper> _logger;
private readonly TaskCompletionSource<ClientInformation> _readyTaskCompletionSource;

/// <summary>
/// Re-assign this delegate in the client configuration to change the way the connected shard count is retrived.<br/>
/// You will only need to do this if you are using a custom IShardOrchestrator for your client.
/// </summary>
public Func<Task<int>> GetShardCount { get; set; }

/// <summary>
/// Creates a new instance of <see cref="DiscordClientWrapper"/>.
/// </summary>
Expand All @@ -43,27 +49,26 @@ public DiscordClientWrapper(DiscordClient discordClient, ILogger<DiscordClientWr

_client = discordClient;
_logger = logger;

_readyTaskCompletionSource = new TaskCompletionSource<ClientInformation>(TaskCreationOptions.RunContinuationsAsynchronously);

void AddEventHandler(Type eventArgsType, Delegate eventHandler)
{
IClientErrorHandler errorHandler = discordClient.GetErrorHandler();
ConcurrentDictionary<Type, AsyncEvent> events = discordClient.GetEvents();
FieldInfo orchestratorField = typeof(DiscordClient).GetField("orchestrator", BindingFlags.NonPublic | BindingFlags.Instance)!;
var orchestrator = (IShardOrchestrator)orchestratorField.GetValue(discordClient)!;

Type asyncEventType = typeof(AsyncEvent<,>).MakeGenericType(discordClient.GetType(), eventArgsType);
AsyncEvent asyncEvent = events.GetOrAdd(eventArgsType, _ => (AsyncEvent)Activator.CreateInstance
(
type: asyncEventType,
args: [errorHandler]
)!);
if (orchestrator is SingleShardOrchestrator)
GetShardCount = () => Task.FromResult(1);

asyncEvent.Register(eventHandler);
else if (orchestrator is MultiShardOrchestrator multiShardOrchestrator)
{
FieldInfo shardCountField = typeof(MultiShardOrchestrator).GetField("shardCount", BindingFlags.NonPublic | BindingFlags.Instance)!;
GetShardCount = () => Task.Run(() => (int)(uint)shardCountField.GetValue(multiShardOrchestrator)!);
}

AddEventHandler(typeof(VoiceStateUpdatedEventArgs), new AsyncEventHandler<DiscordClient, VoiceStateUpdatedEventArgs>(OnVoiceStateUpdated));
AddEventHandler(typeof(VoiceServerUpdatedEventArgs), new AsyncEventHandler<DiscordClient, VoiceServerUpdatedEventArgs>(OnVoiceServerUpdated));
AddEventHandler(typeof(GuildDownloadCompletedEventArgs), new AsyncEventHandler<DiscordClient, GuildDownloadCompletedEventArgs>(OnGuildDownloadCompleted));
else
{
GetShardCount = () => Task.Run(async () => (await discordClient.GetGatewayInfoAsync()).ShardCount);
_logger.LogInformation("The DiscordClient is configured to use a non-default Shard Orchestrator - " +
"make sure that this wrapper's GetShardCount property is configured to properly retrieve the shard count");
}
}

/// <inheritdoc/>
Expand All @@ -88,6 +93,7 @@ public async ValueTask<ImmutableArray<ulong>> GetChannelUsersAsync(
return ImmutableArray<ulong>.Empty;
}
}

catch (DiscordException exception)
{
_logger.LogWarning(
Expand Down Expand Up @@ -152,20 +158,20 @@ public ValueTask<ClientInformation> WaitForReadyAsync(CancellationToken cancella
return new(_readyTaskCompletionSource.Task.WaitAsync(cancellationToken));
}

private async Task OnGuildDownloadCompleted(DiscordClient discordClient, GuildDownloadCompletedEventArgs eventArgs)
internal async Task OnGuildDownloadCompleted(DiscordClient discordClient, GuildDownloadCompletedEventArgs eventArgs)
{
ArgumentNullException.ThrowIfNull(discordClient);
ArgumentNullException.ThrowIfNull(eventArgs);

var clientInformation = new ClientInformation(
Label: "DSharpPlus",
CurrentUserId: discordClient.CurrentUser.Id,
ShardCount: await discordClient.GetShardCountAsync());
ShardCount: await GetShardCount());

_readyTaskCompletionSource.TrySetResult(clientInformation);
}

private async Task OnVoiceServerUpdated(DiscordClient discordClient, VoiceServerUpdatedEventArgs voiceServerUpdateEventArgs)
internal async Task OnVoiceServerUpdated(DiscordClient discordClient, VoiceServerUpdatedEventArgs voiceServerUpdateEventArgs)
{
ArgumentNullException.ThrowIfNull(discordClient);
ArgumentNullException.ThrowIfNull(voiceServerUpdateEventArgs);
Expand All @@ -174,7 +180,7 @@ private async Task OnVoiceServerUpdated(DiscordClient discordClient, VoiceServer
Token: voiceServerUpdateEventArgs.VoiceToken,
Endpoint: voiceServerUpdateEventArgs.Endpoint);

var eventArgs = new L4N.VoiceServerUpdatedEventArgs(
var eventArgs = new Lavalink4NET.VoiceServerUpdatedEventArgs(
guildId: voiceServerUpdateEventArgs.Guild.Id,
voiceServer: server);

Expand All @@ -183,7 +189,7 @@ await VoiceServerUpdated
.ConfigureAwait(false);
}

private async Task OnVoiceStateUpdated(DiscordClient discordClient, VoiceStateUpdatedEventArgs voiceStateUpdateEventArgs)
internal async Task OnVoiceStateUpdated(DiscordClient discordClient, VoiceStateUpdatedEventArgs voiceStateUpdateEventArgs)
{
ArgumentNullException.ThrowIfNull(discordClient);
ArgumentNullException.ThrowIfNull(voiceStateUpdateEventArgs);
Expand All @@ -202,7 +208,7 @@ private async Task OnVoiceStateUpdated(DiscordClient discordClient, VoiceStateUp
SessionId: sessionId);

// invoke event
var eventArgs = new L4N.VoiceStateUpdatedEventArgs(
var eventArgs = new Lavalink4NET.VoiceStateUpdatedEventArgs(
guildId: voiceStateUpdateEventArgs.Guild.Id,
userId: voiceStateUpdateEventArgs.User.Id,
isCurrentUser: voiceStateUpdateEventArgs.User.Id == discordClient.CurrentUser.Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
<!-- Documentation -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackAsTool>False</PackAsTool>
<Version>1.0.4</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02324" />
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02352" />
<ProjectReference Include="../Lavalink4NET/Lavalink4NET.csproj" />
</ItemGroup>
<Import Project="../Lavalink4NET.targets" />
Expand Down
26 changes: 26 additions & 0 deletions src/Lavalink4NET.DSharpPlus.Nightly/Lavalink4NETInvokeHandlers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace Lavalink4NET.DSharpPlus;

using System.Threading.Tasks;
using global::DSharpPlus;
using global::DSharpPlus.EventArgs;
using Lavalink4NET.Clients;

/// <summary>
/// Forwards event triggers to the Lavalink4NET client wrapper
/// </summary>
internal sealed class Lavalink4NETInvokeHandlers(IDiscordClientWrapper wrapper) :
IEventHandler<GuildDownloadCompletedEventArgs>,
IEventHandler<VoiceServerUpdatedEventArgs>,
IEventHandler<VoiceStateUpdatedEventArgs>
{
private readonly DiscordClientWrapper wrapper = (DiscordClientWrapper)wrapper;

public async Task HandleEventAsync(DiscordClient sender, GuildDownloadCompletedEventArgs eventArgs)
=> await wrapper.OnGuildDownloadCompleted(sender, eventArgs);

public async Task HandleEventAsync(DiscordClient sender, VoiceServerUpdatedEventArgs eventArgs)
=> await wrapper.OnVoiceServerUpdated(sender, eventArgs);

public async Task HandleEventAsync(DiscordClient sender, VoiceStateUpdatedEventArgs eventArgs)
=> await wrapper.OnVoiceStateUpdated(sender, eventArgs);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace Lavalink4NET.Extensions;

using System;
using global::DSharpPlus.Extensions;
using Lavalink4NET.DSharpPlus;
using Microsoft.Extensions.DependencyInjection;

Expand All @@ -17,6 +18,10 @@ public static class ServiceCollectionExtensions
public static IServiceCollection AddLavalink(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
return services.AddLavalink<DiscordClientWrapper>();

services.AddLavalink<DiscordClientWrapper>();
services.ConfigureEventHandlers(events => events.AddEventHandlers<Lavalink4NETInvokeHandlers>(ServiceLifetime.Transient));

return services;
}
}

0 comments on commit fa61e65

Please sign in to comment.