Refactoring

This commit is contained in:
BlossomiShymae
2024-08-09 17:59:29 -05:00
parent 39c82a8780
commit 9ba81ff48f
6 changed files with 75 additions and 63 deletions

View File

@@ -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<OopsiesWindowRequestedMessage>, IRecipient<DataReadyMessage>
public partial class ConsoleViewModel : PageBase, IRecipient<DataReadyMessage>
{
public IAvaloniaReadOnlyList<string> RequestMethods { get; } = new AvaloniaList<string>(["GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS", "TRACE"]);
@@ -34,7 +34,6 @@ namespace Needlework.Net.Desktop.ViewModels
{
WindowService = windowService;
WeakReferenceMessenger.Default.Register<OopsiesWindowRequestedMessage, string>(this, nameof(ConsoleView));
WeakReferenceMessenger.Default.Register<DataReadyMessage>(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<object>(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(() =>

View File

@@ -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]

View File

@@ -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<DataRequestMessage>, IRecipient<HostDocumentRequestMessage>
public partial class MainWindowViewModel : ObservableObject, IRecipient<DataRequestMessage>, IRecipient<HostDocumentRequestMessage>, IRecipient<OopsiesWindowRequestedMessage>
{
public IAvaloniaReadOnlyList<PageBase> 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<PageBase> pages, HttpClient httpClient)
public MainWindowViewModel(IEnumerable<PageBase> pages, HttpClient httpClient, WindowService windowService)
{
Pages = new AvaloniaList<PageBase>(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);
}
}
}

View File

@@ -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<object>(responseBody), App.JsonSerializerOptions) : string.Empty;
responseBody = JsonSerializer.Serialize(JsonSerializer.Deserialize<object>(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)
{

View File

@@ -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<string, EventMessage> _events = [];
public WebsocketClient? Client { get; set; }
public WindowService WindowService { get; }
public List<string> 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)

View File

@@ -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<ResponseUpdatedMessag
public void Receive(ResponseUpdatedMessage message)
{
if (!string.IsNullOrEmpty(message.Value))
{
var text = JsonSerializer.Serialize(JsonSerializer.Deserialize<object>(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)