83 lines
2.3 KiB
C#
83 lines
2.3 KiB
C#
using System.Diagnostics;
|
|
using System.Management;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
|
|
namespace LeagueAPI;
|
|
|
|
public record WebsocketMessageResult(byte[] Message, WebSocketMessageType MessageType);
|
|
|
|
public static class Extensions
|
|
{
|
|
extension(Process process)
|
|
{
|
|
public string GetCommandLine()
|
|
{
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
throw new PlatformNotSupportedException("Only supported on Windows.");
|
|
}
|
|
using ManagementObjectSearcher searcher = new("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id);
|
|
using ManagementObjectCollection objects = searcher.Get();
|
|
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString() ?? string.Empty;
|
|
}
|
|
}
|
|
|
|
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<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);
|
|
}
|
|
}
|
|
|
|
}
|