101 lines
2.7 KiB
C#
101 lines
2.7 KiB
C#
using System.Net.WebSockets;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
namespace LeagueAPI;
|
|
|
|
public record WebsocketMessageResult(byte[] Message, WebSocketMessageType MessageType);
|
|
|
|
public static class Extensions
|
|
{
|
|
extension(string? s)
|
|
{
|
|
public int ParseInt(int defaultValue = default)
|
|
{
|
|
if (s is null || !int.TryParse(s, out int i))
|
|
{
|
|
return defaultValue;
|
|
}
|
|
return i;
|
|
}
|
|
|
|
public string AsFormatWith(params object?[] args)
|
|
{
|
|
if (s is null)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
return string.Format(s, args);
|
|
}
|
|
}
|
|
|
|
extension<TSource>(IEnumerable<TSource?> source)
|
|
{
|
|
/// <summary>
|
|
/// Uses <see cref="Enumerable.Aggregate{TSource}(IEnumerable{TSource}, Func{TSource, TSource, TSource})"/>, evaluates immediately.
|
|
/// </summary>
|
|
public IEnumerable<TSource> WhereNotNull()
|
|
{
|
|
return source.Aggregate(Enumerable.Empty<TSource>(), Accumulate);
|
|
|
|
static IEnumerable<TSource> Accumulate(IEnumerable<TSource> accumulator, TSource? next)
|
|
{
|
|
if (next is not null)
|
|
{
|
|
return accumulator.Append(next);
|
|
}
|
|
return accumulator;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Uses lazy-evaluation
|
|
/// </summary>
|
|
public IEnumerable<TSource> WhereNotNullLazy()
|
|
{
|
|
foreach (TSource? element in source)
|
|
{
|
|
if (element is not null)
|
|
{
|
|
yield return element;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension<T>(Task<T> task)
|
|
{
|
|
public T WaitForResult()
|
|
{
|
|
return task.GetAwaiter().GetResult();
|
|
}
|
|
}
|
|
|
|
extension(WebSocket socket)
|
|
{
|
|
public async Task<WebsocketMessageResult> ReadFullMessage(CancellationToken cancellationToken)
|
|
{
|
|
byte[] buffer = new byte[1024 * 8];
|
|
using MemoryStream memoryStream = new();
|
|
ValueWebSocketReceiveResult receiveResult;
|
|
|
|
do
|
|
{
|
|
Memory<byte> memoryBuffer = new(buffer);
|
|
receiveResult = await socket.ReceiveAsync(memoryBuffer, cancellationToken);
|
|
|
|
memoryStream.Write(buffer, 0, receiveResult.Count);
|
|
}
|
|
while (!receiveResult.EndOfMessage);
|
|
|
|
if (receiveResult.MessageType is WebSocketMessageType.Close)
|
|
{
|
|
return new([], receiveResult.MessageType);
|
|
}
|
|
|
|
byte[] fullMessageBytes = memoryStream.ToArray();
|
|
return new(fullMessageBytes, receiveResult.MessageType);
|
|
}
|
|
}
|
|
|
|
}
|