diff --git a/ARAMUtility/View/MainWindow.xaml b/ARAMUtility/View/MainWindow.xaml
index e1d7d6d..5157330 100644
--- a/ARAMUtility/View/MainWindow.xaml
+++ b/ARAMUtility/View/MainWindow.xaml
@@ -67,6 +67,7 @@
+
diff --git a/ARAMUtility/ViewModel/MainViewModel.cs b/ARAMUtility/ViewModel/MainViewModel.cs
index d563ecc..5247101 100644
--- a/ARAMUtility/ViewModel/MainViewModel.cs
+++ b/ARAMUtility/ViewModel/MainViewModel.cs
@@ -58,7 +58,6 @@ public partial class MainViewModel : ObservableObject, IDisposable
private readonly LcuWebsocket _lcuWebsocket = new();
private Task _lcuWebsocketTask;
private readonly ARAMBalanceService _aramBalanceService = new();
- private readonly ProcessWatcher _leagueWatcher = new();
private readonly CachingHttpClient _localCachingClient = new(insecure: true);
public MainViewModel()
@@ -74,9 +73,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
File.AppendAllText("socketerror.log", $"[{DateTime.Now:s}] {e.Message}\n{e.StackTrace}\n\n");
};
#endif
- _lcuWebsocketTask = _lcuWebsocket.Connect();
-
- _leagueWatcher.LeagueOfLegendsExeFound += UpdateChampionListsFromGame;
+ _lcuWebsocketTask = _lcuWebsocket.ConnectAsync();
}
internal async void OnInit(object? sender, RoutedEventArgs e)
@@ -102,6 +99,9 @@ public partial class MainViewModel : ObservableObject, IDisposable
{
await FillChampionLists();
}
+
+ await _lcuWebsocket.SubscribeAsync("/lol-matchmaking/v1/ready-check".GetLcuEventName());
+ await _lcuWebsocket.SubscribeAsync("/lol-champ-select/v1/session".GetLcuEventName());
}
private void UpdateConnectionStatus(bool isConnected, ConnectionStatus status)
@@ -113,7 +113,12 @@ public partial class MainViewModel : ObservableObject, IDisposable
});
}
- private async void OnLcuApiEvent(object? sender, LcuApiEvent apiEvent)
+ private void OnLcuApiEvent(object? sender, LcuApiEvent apiEvent)
+ {
+ _ = ProcessLcuApiEvent(apiEvent);
+ }
+
+ private async Task ProcessLcuApiEvent(LcuApiEvent apiEvent)
{
switch (apiEvent.Uri)
{
@@ -140,7 +145,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
await ShowChampionsAsync(session);
break;
default:
- File.AppendAllText("socket.log", $"{apiEvent.Uri}: {apiEvent.EventType} - {apiEvent.Data?.ToJsonString()}\n");
+ File.AppendAllText("socket.log", $"{apiEvent.Uri}: {apiEvent.EventType} - {apiEvent.Data.GetRawText()}\n");
break;
}
}
@@ -232,7 +237,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
}
}
- private async void UpdateChampionListsFromGame(object? sender, EventArgs e)
+ [RelayCommand(AllowConcurrentExecutions = false)]
+ private async Task UpdateChampionListsFromGame()
{
await Task.Delay(TimeSpan.FromSeconds(5));
string playerlistJson = await _localCachingClient.GetStringAsync("https://127.0.0.1:2999/liveclientdata/playerlist", TimeSpan.FromSeconds(30));
@@ -270,7 +276,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (_lcuWebsocketTask is null || _lcuWebsocketTask.IsCompleted)
{
_lcuWebsocketTask?.Dispose();
- _lcuWebsocketTask = _lcuWebsocket.Connect();
+ _lcuWebsocketTask = _lcuWebsocket.ConnectAsync();
}
}
diff --git a/LeagueAPI/APIClient.cs b/LeagueAPI/APIClient.cs
index 9879ab7..cd818b7 100644
--- a/LeagueAPI/APIClient.cs
+++ b/LeagueAPI/APIClient.cs
@@ -82,6 +82,11 @@ public class APIClient : IDisposable
await _lcuHttpClient.PostAsJsonAsync("/lol-matchmaking/v1/ready-check/accept", "");
}
+ public async Task ChampSelectBenchSwap(int championId)
+ {
+ await _lcuHttpClient.PostAsJsonAsync($"/lol-champ-select/v1/session/bench/swap/{championId}", "");
+ }
+
#region DDragon
private async Task DDragonGetAsync(string path)
{
diff --git a/LeagueAPI/CachingHttpClient.cs b/LeagueAPI/CachingHttpClient.cs
index 7ec2ef9..6d3ef87 100644
--- a/LeagueAPI/CachingHttpClient.cs
+++ b/LeagueAPI/CachingHttpClient.cs
@@ -49,6 +49,7 @@ public class CachingHttpClient : IDisposable
{
_cache[requestUri] = new(result);
}
+ ResourceService.SetHttpCache(_cache);
return result;
}
diff --git a/LeagueAPI/Extensions.cs b/LeagueAPI/Extensions.cs
index 0ae9cff..eece129 100644
--- a/LeagueAPI/Extensions.cs
+++ b/LeagueAPI/Extensions.cs
@@ -1,9 +1,8 @@
using System.Net.WebSockets;
-using System.Runtime.CompilerServices;
namespace LeagueAPI;
-public record WebsocketMessageResult(byte[] Message, WebSocketMessageType MessageType);
+public readonly record struct WebsocketMessageResult(byte[] Message, WebSocketMessageType MessageType);
public static class Extensions
{
@@ -18,7 +17,7 @@ public static class Extensions
return i;
}
- public string AsFormatWith(params object?[] args)
+ public string FormatWith(params object?[] args)
{
if (s is null)
{
@@ -26,6 +25,15 @@ public static class Extensions
}
return string.Format(s, args);
}
+
+ public string GetLcuEventName()
+ {
+ if (s is null)
+ {
+ return string.Empty;
+ }
+ return $"OnJsonApiEvent{s.Replace('/', '_')}";
+ }
}
extension(IEnumerable source)
@@ -80,8 +88,12 @@ public static class Extensions
do
{
- Memory memoryBuffer = new(buffer);
- receiveResult = await socket.ReceiveAsync(memoryBuffer, cancellationToken);
+ receiveResult = await socket.ReceiveAsync(buffer.AsMemory(), cancellationToken);
+
+ if (receiveResult.MessageType is WebSocketMessageType.Close)
+ {
+ break;
+ }
memoryStream.Write(buffer, 0, receiveResult.Count);
}
@@ -96,5 +108,4 @@ public static class Extensions
return new(fullMessageBytes, receiveResult.MessageType);
}
}
-
}
diff --git a/LeagueAPI/LcuApiEvent.cs b/LeagueAPI/LcuApiEvent.cs
new file mode 100644
index 0000000..e9bb2aa
--- /dev/null
+++ b/LeagueAPI/LcuApiEvent.cs
@@ -0,0 +1,16 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace LeagueAPI;
+
+public readonly record struct LcuApiEvent
+{
+ [JsonPropertyName("data")]
+ public JsonElement Data { get; init; }
+
+ [JsonPropertyName("eventType")]
+ public required string EventType { get; init; }
+
+ [JsonPropertyName("uri")]
+ public required string Uri { get; init; }
+}
diff --git a/LeagueAPI/LcuRoute.cs b/LeagueAPI/LcuRoute.cs
new file mode 100644
index 0000000..735272e
--- /dev/null
+++ b/LeagueAPI/LcuRoute.cs
@@ -0,0 +1,28 @@
+namespace LeagueAPI;
+
+public static class LcuRoutes
+{
+ public static class Matchmaking
+ {
+ public const string READY_CHECK_URL = "/lol-matchmaking/v1/ready-check";
+ }
+
+ public static class ChampSelect
+ {
+ public const string ALL_GRID_CHAMPIONS_URL = "/lol-champ-select/v1/all-grid-champions";
+ public const string BANNABLE_CHAPIONIDS_URL = "/lol-champ-select/v1/bannable-champion-ids";
+ public const string CURRENT_CHAMPION_URL = "/lol-champ-select/v1/current-champion";
+ public const string DISABLED_CHAMPION_IDS_URL = "/lol-champ-select/v1/disabled-champion-ids";
+ public const string GRID_CHAMPIONS_URL = "/lol-champ-select/v1/grid-champions";
+ public const string MUTED_PLAYERS_URL = "/lol-champ-select/v1/muted-players";
+ public const string ONGOING_CHAMPION_SWAP_URL = "/lol-champ-select/v1/ongoing-champion-swap";
+ public const string PICKABLE_CHAMPION_IDS_URL = "/lol-champ-select/v1/pickable-champion-ids";
+ public const string PIN_DROP_NOTIFICATION_URL = "/lol-champ-select/v1/pin-drop-notification";
+ public const string SESSION_URL = "/lol-champ-select/v1/session";
+ public const string SFX_NOTIFICATIONS_URL = "/lol-champ-select/v1/sfx-notifications";
+ public const string SKIN_CAROUSEL_SKINS_URL = "/lol-champ-select/v1/skin-carousel-skins";
+ public const string SKIN_SELECTOR_INFO_URL = "/lol-champ-select/v1/skin-selector-info";
+ public const string SUMMONERS_URL = "/lol-champ-select/v1/summoners";
+ public const string TEAM_BOOST_URL = "/lol-champ-select/v1/team-boost";
+ }
+}
diff --git a/LeagueAPI/LcuWebsocket.cs b/LeagueAPI/LcuWebsocket.cs
index 3eeb612..4c1b5fe 100644
--- a/LeagueAPI/LcuWebsocket.cs
+++ b/LeagueAPI/LcuWebsocket.cs
@@ -11,22 +11,22 @@ public class LcuWebsocket : IDisposable
private const int OPCODE_SUBSCRIBE = 5;
private const int OPCODE_UNSUBSCRIBE = 6;
private const int OPCODE_SEND = 8;
- private static readonly IReadOnlyList SUBSCRIBE_EVENTS =
- [
- "OnJsonApiEvent_lol-champ-select_v1_session",
- "OnJsonApiEvent_lol-matchmaking_v1_ready-check",
- ];
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;
public event EventHandler? LcuApiException;
+ private readonly HashSet _subscribedEvents = [];
+ public IReadOnlyCollection SubscribedEvents => _subscribedEvents;
+
[MemberNotNull(nameof(RiotAuthentication))]
public ProcessInfo? ProcessInfo { get; internal set; }
public RiotAuthentication? RiotAuthentication
@@ -42,7 +42,7 @@ public class LcuWebsocket : IDisposable
}
}
- public async Task Connect()
+ public async Task ConnectAsync()
{
Connecting?.Invoke(this, EventArgs.Empty);
try
@@ -70,12 +70,9 @@ public class LcuWebsocket : IDisposable
{
await _socket.ConnectAsync(uri, CancellationToken.None);
- foreach (string eventName in SUBSCRIBE_EVENTS)
+ foreach (string eventName in _subscribedEvents)
{
- string message = $"[{OPCODE_SUBSCRIBE}, \"{eventName}\"]";
- byte[] buffer = Encoding.UTF8.GetBytes(message);
- Memory memory = new(buffer);
- await _socket.SendAsync(memory, WebSocketMessageType.Text, true, CancellationToken.None);
+ await SendSubscribeAsync(eventName);
}
Connected?.Invoke(this, EventArgs.Empty);
@@ -88,30 +85,44 @@ public class LcuWebsocket : IDisposable
if (result.MessageType is WebSocketMessageType.Close)
{
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
+ break;
}
- else
+
+ if (result.Message.Length == 0)
{
- if (result.Message.Length == 0)
- {
- continue;
- }
-
- JsonElement response = JsonElement.Parse(result.Message);
- if (response.ValueKind != JsonValueKind.Array
- || response.GetArrayLength() != 3
- || !response[0].TryGetInt32(out int value)
- || value != OPCODE_SEND)
- {
- continue;
- }
- LcuApiEvent? apiEvent = response[2].Deserialize();
- if (apiEvent is null)
- {
- continue;
- }
-
- LcuApiEvent?.Invoke(this, apiEvent);
+ continue;
}
+
+ ReadOnlySpan 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(ref reader);
+ if (apiEvent is not LcuApiEvent lcuApiEvent)
+ {
+ continue;
+ }
+
+ LcuApiEvent?.Invoke(this, lcuApiEvent);
}
catch (Exception ex)
{
@@ -129,6 +140,66 @@ public class LcuWebsocket : IDisposable
}
}
+ 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);
+ }
+ }
+ }
+
+ ///
+ /// Adds the event to .
+ /// If the websocket is connected, it actively subscribes to this event.
+ /// If it's not connected, it will subscribe the next time it connects.
+ ///
+ /// The LCU event name.
+ 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);
+ }
+
+ ///
+ /// Removes the event from .
+ /// 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.
+ ///
+ /// The LCU event name.
+ 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)
{
diff --git a/LeagueAPI/LeagueAPI.csproj b/LeagueAPI/LeagueAPI.csproj
index 02cb419..0fe9596 100644
--- a/LeagueAPI/LeagueAPI.csproj
+++ b/LeagueAPI/LeagueAPI.csproj
@@ -4,10 +4,23 @@
net10.0
enable
enable
+ true
-
-
-
+
+ false
+ true
+ LeagueAPI
+ SacredFloof
+ SacredFloof
+ Access to the League of Legends client API
+ SacredFloof 2026
+ API;LeagueOfLegends
+ 1.0.7
+
+
+
+
+
diff --git a/LeagueAPI/LeagueEvent.cs b/LeagueAPI/LeagueEvent.cs
deleted file mode 100644
index e94019e..0000000
--- a/LeagueAPI/LeagueEvent.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using System.Text.Json.Nodes;
-using System.Text.Json.Serialization;
-
-namespace LeagueAPI;
-
-public record class LcuApiEvent
-{
- [JsonPropertyName("data")]
- public JsonNode? Data { get; init; }
-
- [JsonPropertyName("eventType")]
- public string? EventType { get; init; }
-
- [JsonPropertyName("uri")]
- public string? Uri { get; init; }
-}
diff --git a/LeagueAPI/ResourceService.cs b/LeagueAPI/ResourceService.cs
index c0150cf..33f2116 100644
--- a/LeagueAPI/ResourceService.cs
+++ b/LeagueAPI/ResourceService.cs
@@ -22,14 +22,14 @@ public static class ResourceService
public static async Task GetChampionIconPathAsync(int championId = -1)
{
- FileInfo assetFile = new(Path.Combine(AssetDirectory.FullName, CHAMPION_FILENAME_FORMAT.AsFormatWith(championId)));
+ FileInfo assetFile = new(Path.Combine(AssetDirectory.FullName, CHAMPION_FILENAME_FORMAT.FormatWith(championId)));
if (assetFile.Exists)
{
return assetFile.FullName;
}
using HttpClient client = new();
- HttpResponseMessage response = await client.GetAsync(DDRAGON_CHAMPION_URL.AsFormatWith(championId));
+ HttpResponseMessage response = await client.GetAsync(DDRAGON_CHAMPION_URL.FormatWith(championId));
if (!response.IsSuccessStatusCode)
{
return string.Empty;