231 lines
7.3 KiB
C#
231 lines
7.3 KiB
C#
using System.Diagnostics.CodeAnalysis;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using LeagueAPI.Utils;
|
|
|
|
namespace LeagueAPI;
|
|
|
|
public class LcuWebsocket : IDisposable
|
|
{
|
|
private const int OPCODE_SUBSCRIBE = 5;
|
|
private const int OPCODE_UNSUBSCRIBE = 6;
|
|
private const int OPCODE_SEND = 8;
|
|
|
|
private bool _isDisposed;
|
|
|
|
private readonly ClientWebSocket _socket = new();
|
|
|
|
public bool IsConnected => _socket.State == WebSocketState.Open;
|
|
|
|
public event EventHandler? Connecting;
|
|
public event EventHandler? Connected;
|
|
public event EventHandler? Disconnected;
|
|
public event EventHandler<LcuApiEvent>? LcuApiEvent;
|
|
public event EventHandler<Exception>? LcuApiException;
|
|
|
|
private readonly HashSet<string> _subscribedEvents = [];
|
|
public IReadOnlyCollection<string> SubscribedEvents => _subscribedEvents;
|
|
|
|
[MemberNotNull(nameof(RiotAuthentication))]
|
|
public ProcessInfo? ProcessInfo { get; internal set; }
|
|
public RiotAuthentication? RiotAuthentication
|
|
{
|
|
get
|
|
{
|
|
if (ProcessInfo is not null)
|
|
{
|
|
return new RiotAuthentication(ProcessInfo.RemotingAuthToken);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task ConnectAsync()
|
|
{
|
|
Connecting?.Invoke(this, EventArgs.Empty);
|
|
try
|
|
{
|
|
ProcessInfo = ProcessFinder.GetProcessInfo();
|
|
}
|
|
catch
|
|
{
|
|
await Task.Delay(TimeSpan.FromMilliseconds(500));
|
|
Disconnected?.Invoke(this, EventArgs.Empty);
|
|
return;
|
|
}
|
|
if (!ProcessFinder.IsPortOpen(ProcessInfo))
|
|
{
|
|
Disconnected?.Invoke(this, EventArgs.Empty);
|
|
throw new InvalidOperationException("Failed to connect to LCUx process port.");
|
|
}
|
|
|
|
// ignore SSL certificate errors
|
|
_socket.Options.RemoteCertificateValidationCallback = (_, _, _, _) => true;
|
|
_socket.Options.Credentials = RiotAuthentication.ToNetworkCredential();
|
|
|
|
Uri uri = new($"wss://127.0.0.1:{ProcessInfo.AppPort}/");
|
|
try
|
|
{
|
|
await _socket.ConnectAsync(uri, CancellationToken.None);
|
|
|
|
foreach (string eventName in _subscribedEvents)
|
|
{
|
|
await SendSubscribeAsync(eventName);
|
|
}
|
|
|
|
Connected?.Invoke(this, EventArgs.Empty);
|
|
|
|
while (_socket.State is WebSocketState.Open)
|
|
{
|
|
try
|
|
{
|
|
WebsocketMessageResult result = await _socket.ReadFullMessage(CancellationToken.None);
|
|
if (result.MessageType is WebSocketMessageType.Close)
|
|
{
|
|
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
|
break;
|
|
}
|
|
|
|
if (result.Message.Length == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
ReadOnlySpan<byte> jsonSpan = result.Message;
|
|
Utf8JsonReader reader = new(jsonSpan);
|
|
// read array start
|
|
if (!reader.Read() || reader.TokenType is not JsonTokenType.StartArray)
|
|
{
|
|
continue;
|
|
}
|
|
// read first item: opcode
|
|
if (!reader.Read() || reader.TokenType is not JsonTokenType.Number || !reader.TryGetInt32(out int value) || value != OPCODE_SEND)
|
|
{
|
|
continue;
|
|
}
|
|
// skip second item (string api event name)
|
|
if (!reader.Read() || !reader.TrySkip())
|
|
{
|
|
continue;
|
|
}
|
|
// read third item: payload
|
|
if (!reader.Read())
|
|
{
|
|
continue;
|
|
}
|
|
|
|
LcuApiEvent? apiEvent = JsonSerializer.Deserialize<LcuApiEvent>(ref reader);
|
|
if (apiEvent is not LcuApiEvent lcuApiEvent)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
LcuApiEvent?.Invoke(this, lcuApiEvent);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LcuApiException?.Invoke(this, ex);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is not WebSocketException)
|
|
{
|
|
LcuApiException?.Invoke(this, ex);
|
|
}
|
|
finally
|
|
{
|
|
Disconnected?.Invoke(this, EventArgs.Empty);
|
|
}
|
|
}
|
|
|
|
public async Task DisconnectAsync()
|
|
{
|
|
if (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
|
|
{
|
|
try
|
|
{
|
|
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LcuApiException?.Invoke(this, ex);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds the event to <see cref="SubscribedEvents"/>.
|
|
/// If the websocket is connected, it actively subscribes to this event.
|
|
/// If it's not connected, it will subscribe the next time it connects.
|
|
/// </summary>
|
|
/// <param name="eventName">The LCU event name.</param>
|
|
public async Task SubscribeAsync(string eventName)
|
|
{
|
|
bool isAdded = _subscribedEvents.Add(eventName);
|
|
|
|
if (!IsConnected || !isAdded)
|
|
{
|
|
return;
|
|
}
|
|
|
|
await SendSubscribeAsync(eventName);
|
|
}
|
|
|
|
private async Task SendSubscribeAsync(string eventName)
|
|
{
|
|
string message = $"[{OPCODE_SUBSCRIBE}, \"{eventName}\"]";
|
|
byte[] buffer = Encoding.UTF8.GetBytes(message);
|
|
await _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes the event from <see cref="SubscribedEvents"/>.
|
|
/// If the websocket is connected, it actively unsubscribes from this event.
|
|
/// If it's not connected, it will no longer subscribe to it the next time it connects.
|
|
/// </summary>
|
|
/// <param name="eventName">The LCU event name.</param>
|
|
public async Task UnsubscribeAsync(string eventName)
|
|
{
|
|
bool isRemoved = _subscribedEvents.Remove(eventName);
|
|
|
|
if (!IsConnected || !isRemoved)
|
|
{
|
|
return;
|
|
}
|
|
|
|
string message = $"[{OPCODE_UNSUBSCRIBE}, \"{eventName}\"]";
|
|
byte[] buffer = Encoding.UTF8.GetBytes(message);
|
|
await _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
|
|
}
|
|
|
|
#region IDisposable
|
|
protected virtual void Dispose(bool disposing)
|
|
{
|
|
if (!_isDisposed)
|
|
{
|
|
if (disposing)
|
|
{
|
|
if (_socket.State == WebSocketState.Open)
|
|
{
|
|
_socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None)
|
|
.Wait();
|
|
}
|
|
_socket?.Dispose();
|
|
ProcessInfo = null;
|
|
}
|
|
|
|
_isDisposed = true;
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
|
|
Dispose(disposing: true);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
#endregion
|
|
}
|