Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PromptClientInput method in Utilities.cs #330

Merged
merged 1 commit into from
Jul 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}
}
}
Loading