From 9ba81ff48f436bfc4744861cb548b778a4796be6 Mon Sep 17 00:00:00 2001 From: BlossomiShymae <87099578+BlossomiShymae@users.noreply.github.com> Date: Fri, 9 Aug 2024 17:59:29 -0500 Subject: [PATCH] Refactoring --- .../ViewModels/ConsoleViewModel.cs | 15 +++--- .../ViewModels/HomeViewModel.cs | 48 +++++++++---------- .../ViewModels/MainWindowViewModel.cs | 13 ++++- .../ViewModels/PathOperationViewModel.cs | 11 ++--- .../ViewModels/WebsocketViewModel.cs | 38 +++++++++++---- .../Views/ConsoleView.axaml.cs | 13 +---- 6 files changed, 75 insertions(+), 63 deletions(-) diff --git a/Needlework.Net.Desktop/ViewModels/ConsoleViewModel.cs b/Needlework.Net.Desktop/ViewModels/ConsoleViewModel.cs index 4787a58..aec7d93 100644 --- a/Needlework.Net.Desktop/ViewModels/ConsoleViewModel.cs +++ b/Needlework.Net.Desktop/ViewModels/ConsoleViewModel.cs @@ -5,16 +5,16 @@ using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; using Needlework.Net.Desktop.Messages; using Needlework.Net.Desktop.Services; -using Needlework.Net.Desktop.Views; using SukiUI.Controls; using System; using System.Net.Http; +using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Needlework.Net.Desktop.ViewModels { - public partial class ConsoleViewModel : PageBase, IRecipient, IRecipient + public partial class ConsoleViewModel : PageBase, IRecipient { public IAvaloniaReadOnlyList RequestMethods { get; } = new AvaloniaList(["GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS", "TRACE"]); @@ -34,7 +34,6 @@ namespace Needlework.Net.Desktop.ViewModels { WindowService = windowService; - WeakReferenceMessenger.Default.Register(this, nameof(ConsoleView)); WeakReferenceMessenger.Default.Register(this); } @@ -66,10 +65,13 @@ namespace Needlework.Net.Desktop.ViewModels var riotAuthentication = new RiotAuthentication(processInfo.RemotingAuthToken); var body = await response.Content.ReadAsStringAsync(); + body = JsonSerializer.Serialize(JsonSerializer.Deserialize(body, App.JsonSerializerOptions)); + if (body.Length >= App.MaxCharacters) WindowService.ShowOopsiesWindow(body); + else WeakReferenceMessenger.Default.Send(new ResponseUpdatedMessage(body), nameof(ConsoleViewModel)); + ResponseStatus = response.StatusCode.ToString(); ResponsePath = $"https://127.0.0.1:{processInfo.AppPort}{RequestPath}"; ResponseAuthentication = $"Basic {riotAuthentication.Value}"; - WeakReferenceMessenger.Default.Send(new ResponseUpdatedMessage(body), nameof(ConsoleViewModel)); } catch (Exception ex) { @@ -85,11 +87,6 @@ namespace Needlework.Net.Desktop.ViewModels } } - public void Receive(OopsiesWindowRequestedMessage message) - { - WindowService.ShowOopsiesWindow(message.Value); - } - public void Receive(DataReadyMessage message) { Avalonia.Threading.Dispatcher.UIThread.Invoke(() => diff --git a/Needlework.Net.Desktop/ViewModels/HomeViewModel.cs b/Needlework.Net.Desktop/ViewModels/HomeViewModel.cs index 87ad2e6..fe34432 100644 --- a/Needlework.Net.Desktop/ViewModels/HomeViewModel.cs +++ b/Needlework.Net.Desktop/ViewModels/HomeViewModel.cs @@ -16,40 +16,36 @@ namespace Needlework.Net.Desktop.ViewModels public HomeViewModel() : base("Home", Material.Icons.MaterialIconKind.Home, int.MinValue) { - StartProcessing(); + var thread = new Thread(StartProcessing) { IsBackground = true }; + thread.Start(); } private void StartProcessing() { - var thread = new Thread(() => + while (true) { - while (true) + void Set(string text, Color color, string address) { - void Set(string text, Color color, string address) + Avalonia.Threading.Dispatcher.UIThread.Invoke(() => { - Avalonia.Threading.Dispatcher.UIThread.Invoke(() => - { - StatusText = text; - StatusForeground = new SolidColorBrush(color.ToUInt32()); - StatusAddress = address; - }); - } - - try - { - var processInfo = Connector.GetProcessInfo(); - Set("Online", Colors.Green, $"https://127.0.0.1:{processInfo.AppPort}/"); - } - catch (InvalidOperationException) - { - Set("Offline", Colors.Red, "N/A"); - } - - Thread.Sleep(TimeSpan.FromSeconds(5)); + StatusText = text; + StatusForeground = new SolidColorBrush(color.ToUInt32()); + StatusAddress = address; + }); } - }) - { IsBackground = true }; - thread.Start(); + + try + { + var processInfo = Connector.GetProcessInfo(); + Set("Online", Colors.Green, $"https://127.0.0.1:{processInfo.AppPort}/"); + } + catch (InvalidOperationException) + { + Set("Offline", Colors.Red, "N/A"); + } + + Thread.Sleep(TimeSpan.FromSeconds(5)); + } } [RelayCommand] diff --git a/Needlework.Net.Desktop/ViewModels/MainWindowViewModel.cs b/Needlework.Net.Desktop/ViewModels/MainWindowViewModel.cs index 63ce3c0..91cd820 100644 --- a/Needlework.Net.Desktop/ViewModels/MainWindowViewModel.cs +++ b/Needlework.Net.Desktop/ViewModels/MainWindowViewModel.cs @@ -5,6 +5,7 @@ using CommunityToolkit.Mvvm.Messaging; using Microsoft.OpenApi.Models; using Needlework.Net.Core; using Needlework.Net.Desktop.Messages; +using Needlework.Net.Desktop.Services; using SukiUI.Controls; using System; using System.Collections.Generic; @@ -16,21 +17,23 @@ using System.Threading.Tasks; namespace Needlework.Net.Desktop.ViewModels { - public partial class MainWindowViewModel : ObservableObject, IRecipient, IRecipient + public partial class MainWindowViewModel : ObservableObject, IRecipient, IRecipient, IRecipient { public IAvaloniaReadOnlyList Pages { get; } public string Version { get; } = Assembly.GetEntryAssembly()?.GetName().Version?.ToString() ?? "0.0.0.0"; public HttpClient HttpClient { get; } + public WindowService WindowService { get; } public LcuSchemaHandler? LcuSchemaHandler { get; set; } public OpenApiDocument? HostDocument { get; set; } [ObservableProperty] private bool _isBusy = true; - public MainWindowViewModel(IEnumerable pages, HttpClient httpClient) + public MainWindowViewModel(IEnumerable pages, HttpClient httpClient, WindowService windowService) { Pages = new AvaloniaList(pages.OrderBy(x => x.Index).ThenBy(x => x.DisplayName)); HttpClient = httpClient; + WindowService = windowService; WeakReferenceMessenger.Default.RegisterAll(this); Task.Run(FetchDataAsync); @@ -42,6 +45,7 @@ namespace Needlework.Net.Desktop.ViewModels HostDocument = document; var handler = new LcuSchemaHandler(document); LcuSchemaHandler = handler; + WeakReferenceMessenger.Default.Send(new DataReadyMessage(handler)); await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () => await SukiHost.ShowToast("OpenAPI Data Processed", "Some pages can now be used.", SukiUI.Enums.NotificationType.Success, TimeSpan.FromSeconds(5))); IsBusy = false; @@ -75,5 +79,10 @@ namespace Needlework.Net.Desktop.ViewModels { } + + public void Receive(OopsiesWindowRequestedMessage message) + { + WindowService.ShowOopsiesWindow(message.Value); + } } } diff --git a/Needlework.Net.Desktop/ViewModels/PathOperationViewModel.cs b/Needlework.Net.Desktop/ViewModels/PathOperationViewModel.cs index 5d9fe03..0d113e9 100644 --- a/Needlework.Net.Desktop/ViewModels/PathOperationViewModel.cs +++ b/Needlework.Net.Desktop/ViewModels/PathOperationViewModel.cs @@ -50,10 +50,7 @@ namespace Needlework.Net.Desktop.ViewModels var processInfo = Connector.GetProcessInfo(); return processInfo; } - catch (Exception ex) - { - Task.Run(async () => await SukiHost.ShowToast("Error", ex.Message, SukiUI.Enums.NotificationType.Error)); - } + catch (Exception) { } return null; } @@ -100,14 +97,16 @@ namespace Needlework.Net.Desktop.ViewModels var response = await Connector.SendAsync(method, $"{uri}", content) ?? throw new Exception("Response is null."); var riotAuthentication = new RiotAuthentication(processInfo.RemotingAuthToken); var responseBody = await response.Content.ReadAsStringAsync(); - responseBody = !string.IsNullOrEmpty(responseBody) ? JsonSerializer.Serialize(JsonSerializer.Deserialize(responseBody), App.JsonSerializerOptions) : string.Empty; + + responseBody = JsonSerializer.Serialize(JsonSerializer.Deserialize(responseBody, App.JsonSerializerOptions)); + if (responseBody.Length >= App.MaxCharacters) WeakReferenceMessenger.Default.Send(new OopsiesWindowRequestedMessage(responseBody)); + else WeakReferenceMessenger.Default.Send(new EditorUpdateMessage(new(responseBody, "EndpointResponseEditor"))); ResponseStatus = $"{(int)response.StatusCode} {response.StatusCode}"; ResponsePath = $"https://127.0.0.1:{processInfo.AppPort}{uri}"; ResponseAuthentication = $"Basic {riotAuthentication.Value}"; ResponseUsername = riotAuthentication.Username; ResponsePassword = riotAuthentication.Password; - WeakReferenceMessenger.Default.Send(new EditorUpdateMessage(new(responseBody, "EndpointResponseEditor"))); } catch (Exception ex) { diff --git a/Needlework.Net.Desktop/ViewModels/WebsocketViewModel.cs b/Needlework.Net.Desktop/ViewModels/WebsocketViewModel.cs index 6778e55..1be6d1f 100644 --- a/Needlework.Net.Desktop/ViewModels/WebsocketViewModel.cs +++ b/Needlework.Net.Desktop/ViewModels/WebsocketViewModel.cs @@ -11,6 +11,7 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text.Json; +using System.Threading; using Websocket.Client; namespace Needlework.Net.Desktop.ViewModels @@ -27,6 +28,8 @@ namespace Needlework.Net.Desktop.ViewModels private Dictionary _events = []; + public WebsocketClient? Client { get; set; } + public WindowService WindowService { get; } public List FilteredEventLog => string.IsNullOrWhiteSpace(Search) ? [.. EventLog] : [.. EventLog.Where(x => x.ToLower().Contains(Search.ToLower()))]; @@ -35,13 +38,29 @@ namespace Needlework.Net.Desktop.ViewModels { WindowService = windowService; - var client = Connector.CreateLcuWebsocketClient(); - client.EventReceived.Subscribe(OnMessage); - client.DisconnectionHappened.Subscribe(OnDisconnection); - client.ReconnectionHappened.Subscribe(OnReconnection); + var thread = new Thread(InitializeWebsocket) { IsBackground = true }; + thread.Start(); + } - client.Start(); - client.Send(new EventMessage(RequestType.Subscribe, EventMessage.Kinds.OnJsonApiEvent)); + private void InitializeWebsocket() + { + while (true) + { + try + { + var client = Connector.CreateLcuWebsocketClient(); + client.EventReceived.Subscribe(OnMessage); + client.DisconnectionHappened.Subscribe(OnDisconnection); + client.ReconnectionHappened.Subscribe(OnReconnection); + + client.Start(); + client.Send(new EventMessage(RequestType.Subscribe, EventMessage.Kinds.OnJsonApiEvent)); + Client = client; + return; + } + catch (Exception) { } + Thread.Sleep(TimeSpan.FromSeconds(5)); + } } [RelayCommand] @@ -63,12 +82,15 @@ namespace Needlework.Net.Desktop.ViewModels private void OnReconnection(ReconnectionInfo info) { - Trace.WriteLine($"-- Reconnection --\n{JsonSerializer.Serialize(info, App.JsonSerializerOptions)}"); + Trace.WriteLine($"-- Reconnection --\nType{info.Type}"); } private void OnDisconnection(DisconnectionInfo info) { - Trace.WriteLine($"-- Disconnection --\n{JsonSerializer.Serialize(info, App.JsonSerializerOptions)}"); + Trace.WriteLine($"-- Disconnection --\nType:{info.Type}\nSubProocol:{info.SubProtocol}\nCloseStatus:{info.CloseStatus}\nCloseStatusDescription:{info.CloseStatusDescription}\nExceptionMessage:{info?.Exception?.Message}\n:InnerException:{info?.Exception?.InnerException}"); + Client?.Dispose(); + var thread = new Thread(InitializeWebsocket) { IsBackground = true }; + thread.Start(); } private void OnMessage(EventMessage message) diff --git a/Needlework.Net.Desktop/Views/ConsoleView.axaml.cs b/Needlework.Net.Desktop/Views/ConsoleView.axaml.cs index 18896b3..98167a5 100644 --- a/Needlework.Net.Desktop/Views/ConsoleView.axaml.cs +++ b/Needlework.Net.Desktop/Views/ConsoleView.axaml.cs @@ -9,7 +9,6 @@ using Needlework.Net.Desktop.Extensions; using Needlework.Net.Desktop.Messages; using Needlework.Net.Desktop.ViewModels; using SukiUI; -using System.Text.Json; using TextMateSharp.Grammars; namespace Needlework.Net.Desktop.Views; @@ -26,17 +25,7 @@ public partial class ConsoleView : UserControl, IRecipient(message.Value), App.JsonSerializerOptions); - if (text.Length >= App.MaxCharacters) - { - WeakReferenceMessenger.Default.Send(new OopsiesWindowRequestedMessage(text), nameof(ConsoleView)); - _responseEditor!.Text = string.Empty; - } - else _responseEditor!.Text = text; - } - else _responseEditor!.Text = message.Value; + _responseEditor!.Text = message.Value; } public void Receive(ContentRequestMessage message)