Skip to content

Commit

Permalink
Add PromptClientInput method in Utilities.cs
Browse files Browse the repository at this point in the history
A new utility method named 'PromptClientInput' has been added in the Utilities.cs file. This method accepts client, prompt, and validator as inputs and allows taking action based on client responses. Included subscription and unsubscription to the 'ClientMessaged' game event, and handling of cancellation token to control the execution flow.
  • Loading branch information
Ayymoss committed Jul 6, 2024
1 parent 78c5b43 commit 91568ce
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions SharedLibraryCore/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos.Meta;
using SharedLibraryCore.Events.Game;
using SharedLibraryCore.Events.Server;
using SharedLibraryCore.Exceptions;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Interfaces.Events;
using SharedLibraryCore.Localization;
using SharedLibraryCore.RCon;
using static System.Threading.Tasks.Task;
Expand Down Expand Up @@ -1372,5 +1374,48 @@ public static void ExecuteAfterDelay(int delayMs, Func<CancellationToken, Task>

public static void ExecuteAfterDelay(this Func<CancellationToken, Task> action, int delayMs,
CancellationToken token = default) => ExecuteAfterDelay(delayMs, action, token);

public static async Task<string> PromptClientInput(this EFClient client, string prompt, Func<string, Task<bool>> validator,
CancellationToken token = default)
{
var clientResponse = new ManualResetEventSlim(false);
string response = null;

try
{
IGameEventSubscriptions.ClientMessaged += OnResponse;
await client.TellAsync([prompt], token);

var tokenSource = new CancellationTokenSource(DefaultCommandTimeout);
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(tokenSource.Token, token);

clientResponse.Wait(linkedTokenSource.Token);

return response;
}
finally
{
IGameEventSubscriptions.ClientMessaged -= OnResponse;
}

async Task OnResponse(ClientMessageEvent messageEvent, CancellationToken cancellationToken)
{
if (!messageEvent.Origin.ClientId.Equals(client.ClientId) || cancellationToken.IsCancellationRequested)
{
return;
}

response = messageEvent.Message;

if (await validator(response))
{
clientResponse.Set();
}
else
{
await client.TellAsync([prompt], cancellationToken);
}
}
}
}
}

0 comments on commit 91568ce

Please sign in to comment.