heave API to v3, fix some stuff in making connections

This commit is contained in:
Stanley Dimant
2022-07-06 12:35:37 +02:00
parent 145dc50f8a
commit 0b194b3632
3 changed files with 75 additions and 40 deletions

View File

@@ -96,7 +96,11 @@ namespace MareSynchronos.UI
ImGui.SameLine(); ImGui.SameLine();
ImGui.TextColored(ImGuiColors.ParsedGreen, _apiController.OnlineUsers.ToString()); ImGui.TextColored(ImGuiColors.ParsedGreen, _apiController.OnlineUsers.ToString());
ImGui.SameLine(); ImGui.SameLine();
ImGui.Text("Users Online" + (!isIntroUi ? " (server-wide)" : string.Empty)); ImGui.Text("Users Online,");
ImGui.SameLine();
ColorText(_apiController.SystemInfoDto.CpuUsage.ToString("0.00") + "%", GetCpuLoadColor(_apiController.SystemInfoDto.CpuUsage));
ImGui.SameLine();
ImGui.Text("Load");
ImGui.SameLine(); ImGui.SameLine();
ImGui.Text(")"); ImGui.Text(")");
} }
@@ -123,6 +127,9 @@ namespace MareSynchronos.UI
ImGui.PopTextWrapPos(); ImGui.PopTextWrapPos();
} }
public static Vector4 GetCpuLoadColor(double input) => input < 50 ? ImGuiColors.ParsedGreen :
input < 90 ? ImGuiColors.DalamudYellow : ImGuiColors.DalamudRed;
public static Vector4 GetBoolColor(bool input) => input ? ImGuiColors.ParsedGreen : ImGuiColors.DalamudRed; public static Vector4 GetBoolColor(bool input) => input ? ImGuiColors.ParsedGreen : ImGuiColors.DalamudRed;
public static Vector4 UploadColor((long, long) data) => data.Item1 == 0 ? ImGuiColors.DalamudGrey : public static Vector4 UploadColor((long, long) data) => data.Item1 == 0 ? ImGuiColors.DalamudGrey :

View File

@@ -58,7 +58,7 @@ namespace MareSynchronos.Utils
public bool IsLoggedIn => _clientState.IsLoggedIn; public bool IsLoggedIn => _clientState.IsLoggedIn;
public bool IsPlayerPresent => _clientState.LocalPlayer != null; public bool IsPlayerPresent => _clientState.LocalPlayer != null && _clientState.LocalPlayer.IsValid();
public string PlayerName => _clientState.LocalPlayer?.Name.ToString() ?? "--"; public string PlayerName => _clientState.LocalPlayer?.Name.ToString() ?? "--";

View File

@@ -1,9 +1,11 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Dalamud.Logging;
using MareSynchronos.API; using MareSynchronos.API;
using MareSynchronos.Utils; using MareSynchronos.Utils;
using MareSynchronos.WebAPI.Utils; using MareSynchronos.WebAPI.Utils;
@@ -38,7 +40,7 @@ namespace MareSynchronos.WebAPI
private HubConnection? _fileHub; private HubConnection? _fileHub;
private HubConnection? _heartbeatHub; private HubConnection? _connectionHub;
private HubConnection? _adminHub; private HubConnection? _adminHub;
@@ -46,6 +48,7 @@ namespace MareSynchronos.WebAPI
private HubConnection? _userHub; private HubConnection? _userHub;
private ConnectionDto? _connectionDto; private ConnectionDto? _connectionDto;
public SystemInfoDto SystemInfoDto { get; private set; } = new();
public bool IsModerator => (_connectionDto?.IsAdmin ?? false) || (_connectionDto?.IsModerator ?? false); public bool IsModerator => (_connectionDto?.IsAdmin ?? false) || (_connectionDto?.IsModerator ?? false);
public bool IsAdmin => _connectionDto?.IsAdmin ?? false; public bool IsAdmin => _connectionDto?.IsAdmin ?? false;
@@ -116,7 +119,7 @@ namespace MareSynchronos.WebAPI
: "-"; : "-";
public bool ServerAlive => public bool ServerAlive =>
(_heartbeatHub?.State ?? HubConnectionState.Disconnected) == HubConnectionState.Connected; (_connectionHub?.State ?? HubConnectionState.Disconnected) == HubConnectionState.Connected;
public Dictionary<string, string> ServerDictionary => new Dictionary<string, string>() public Dictionary<string, string> ServerDictionary => new Dictionary<string, string>()
{ { MainServiceUri, MainServer } } { { MainServiceUri, MainServer } }
@@ -125,22 +128,25 @@ namespace MareSynchronos.WebAPI
public string UID => _connectionDto?.UID ?? string.Empty; public string UID => _connectionDto?.UID ?? string.Empty;
private string ApiUri => _pluginConfiguration.ApiUri; private string ApiUri => _pluginConfiguration.ApiUri;
public int OnlineUsers { get; private set; } public int OnlineUsers => SystemInfoDto.OnlineUsers;
public ServerState ServerState public ServerState ServerState
{ {
get get
{ {
var supportedByServer = SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0);
bool hasUid = !string.IsNullOrEmpty(UID);
if (_pluginConfiguration.FullPause) if (_pluginConfiguration.FullPause)
return ServerState.Disconnected; return ServerState.Disconnected;
if (!ServerAlive) if (!ServerAlive)
return ServerState.Offline; return ServerState.Offline;
if (ServerAlive && SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0) && string.IsNullOrEmpty(UID)) if (!hasUid && _pluginConfiguration.ClientSecret.ContainsKey(ApiUri))
return ServerState.Unauthorized; return ServerState.Unauthorized;
if (ServerAlive && !SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0) && !string.IsNullOrEmpty(UID)) if (!supportedByServer)
return ServerState.VersionMisMatch; return ServerState.VersionMisMatch;
if (ServerAlive && SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0) && !string.IsNullOrEmpty(UID)) if (supportedByServer && hasUid)
return ServerState.Connected; return ServerState.Connected;
return ServerState.NoAccount; return ServerState.NoAccount;
} }
} }
@@ -154,25 +160,33 @@ namespace MareSynchronos.WebAPI
_connectionCancellationTokenSource.Cancel(); _connectionCancellationTokenSource.Cancel();
_connectionCancellationTokenSource = new CancellationTokenSource(); _connectionCancellationTokenSource = new CancellationTokenSource();
var token = _connectionCancellationTokenSource.Token; var token = _connectionCancellationTokenSource.Token;
while (ServerState is not ServerState.Connected && !token.IsCancellationRequested)
while (!ServerAlive && !token.IsCancellationRequested)
{ {
await StopAllConnections(_connectionCancellationTokenSource.Token);
try try
{ {
if (_dalamudUtil.PlayerCharacter == null) throw new ArgumentException("Player not initialized");
Logger.Debug("Building connection"); Logger.Debug("Building connection");
_heartbeatHub = BuildHubConnection(ConnectionHubAPI.Path);
while (!_dalamudUtil.IsPlayerPresent && !token.IsCancellationRequested)
{
Logger.Debug("Player not loaded in yet, waiting");
await Task.Delay(TimeSpan.FromSeconds(1), token);
}
if (token.IsCancellationRequested) break;
_connectionHub = BuildHubConnection(ConnectionHubAPI.Path);
_userHub = BuildHubConnection(UserHubAPI.Path); _userHub = BuildHubConnection(UserHubAPI.Path);
_fileHub = BuildHubConnection(FilesHubAPI.Path); _fileHub = BuildHubConnection(FilesHubAPI.Path);
_adminHub = BuildHubConnection(AdminHubAPI.Path); _adminHub = BuildHubConnection(AdminHubAPI.Path);
await _heartbeatHub.StartAsync(token); await _connectionHub.StartAsync(token);
await _userHub.StartAsync(token); await _userHub.StartAsync(token);
await _fileHub.StartAsync(token); await _fileHub.StartAsync(token);
await _adminHub.StartAsync(token); await _adminHub.StartAsync(token);
OnlineUsers = await _userHub.InvokeAsync<int>(UserHubAPI.InvokeGetOnlineUsers, token); _connectionHub.On<SystemInfoDto>(ConnectionHubAPI.OnUpdateSystemInfo, (dto) => SystemInfoDto = dto);
_userHub.On<int>(UserHubAPI.OnUsersOnline, (count) => OnlineUsers = count);
if (_pluginConfiguration.FullPause) if (_pluginConfiguration.FullPause)
{ {
@@ -180,36 +194,51 @@ namespace MareSynchronos.WebAPI
return; return;
} }
_connectionDto = await _heartbeatHub.InvokeAsync<ConnectionDto>(ConnectionHubAPI.InvokeHeartbeat, token); _connectionDto =
await _connectionHub.InvokeAsync<ConnectionDto>(ConnectionHubAPI.InvokeHeartbeat, token);
if (ServerState is ServerState.Connected) // user is authorized && server is legit if (ServerState is ServerState.Connected) // user is authorized && server is legit
{ {
Logger.Debug("Initializing data"); Logger.Debug("Initializing data");
_userHub.On<ClientPairDto, string>(UserHubAPI.OnUpdateClientPairs, UpdateLocalClientPairsCallback); _userHub.On<ClientPairDto, string>(UserHubAPI.OnUpdateClientPairs,
_userHub.On<CharacterCacheDto, string>(UserHubAPI.OnReceiveCharacterData, ReceiveCharacterDataCallback); UpdateLocalClientPairsCallback);
_userHub.On<CharacterCacheDto, string>(UserHubAPI.OnReceiveCharacterData,
ReceiveCharacterDataCallback);
_userHub.On<string>(UserHubAPI.OnRemoveOnlinePairedPlayer, _userHub.On<string>(UserHubAPI.OnRemoveOnlinePairedPlayer,
(s) => PairedClientOffline?.Invoke(s)); (s) => PairedClientOffline?.Invoke(s));
_userHub.On<string>(UserHubAPI.OnAddOnlinePairedPlayer, _userHub.On<string>(UserHubAPI.OnAddOnlinePairedPlayer,
(s) => PairedClientOnline?.Invoke(s)); (s) => PairedClientOnline?.Invoke(s));
_adminHub.On(AdminHubAPI.OnForcedReconnect, UserForcedReconnectCallback); _adminHub.On(AdminHubAPI.OnForcedReconnect, UserForcedReconnectCallback);
PairedClients = await _userHub!.InvokeAsync<List<ClientPairDto>>(UserHubAPI.InvokeGetPairedClients, token); PairedClients =
await _userHub!.InvokeAsync<List<ClientPairDto>>(UserHubAPI.InvokeGetPairedClients, token);
_heartbeatHub.Closed += HeartbeatHubOnClosed; _connectionHub.Closed += ConnectionHubOnClosed;
_heartbeatHub.Reconnected += HeartbeatHubOnReconnected; _connectionHub.Reconnected += ConnectionHubOnReconnected;
_heartbeatHub.Reconnecting += HeartbeatHubOnReconnecting; _connectionHub.Reconnecting += ConnectionHubOnReconnecting;
if (IsModerator) if (IsModerator)
{ {
AdminForbiddenFiles = await _adminHub.InvokeAsync<List<ForbiddenFileDto>>(AdminHubAPI.InvokeGetForbiddenFiles, token); AdminForbiddenFiles =
AdminBannedUsers = await _adminHub.InvokeAsync<List<BannedUserDto>>(AdminHubAPI.InvokeGetBannedUsers, token); await _adminHub.InvokeAsync<List<ForbiddenFileDto>>(AdminHubAPI.InvokeGetForbiddenFiles,
_adminHub.On<BannedUserDto>(AdminHubAPI.OnUpdateOrAddBannedUser, UpdateOrAddBannedUserCallback); token);
AdminBannedUsers =
await _adminHub.InvokeAsync<List<BannedUserDto>>(AdminHubAPI.InvokeGetBannedUsers,
token);
_adminHub.On<BannedUserDto>(AdminHubAPI.OnUpdateOrAddBannedUser,
UpdateOrAddBannedUserCallback);
_adminHub.On<BannedUserDto>(AdminHubAPI.OnDeleteBannedUser, DeleteBannedUserCallback); _adminHub.On<BannedUserDto>(AdminHubAPI.OnDeleteBannedUser, DeleteBannedUserCallback);
_adminHub.On<ForbiddenFileDto>(AdminHubAPI.OnUpdateOrAddForbiddenFile, UpdateOrAddForbiddenFileCallback); _adminHub.On<ForbiddenFileDto>(AdminHubAPI.OnUpdateOrAddForbiddenFile,
_adminHub.On<ForbiddenFileDto>(AdminHubAPI.OnDeleteForbiddenFile, DeleteForbiddenFileCallback); UpdateOrAddForbiddenFileCallback);
_adminHub.On<ForbiddenFileDto>(AdminHubAPI.OnDeleteForbiddenFile,
DeleteForbiddenFileCallback);
} }
Connected?.Invoke(); Connected?.Invoke();
} }
else if (ServerState is ServerState.VersionMisMatch or ServerState.NoAccount or ServerState.Unauthorized)
{
break;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -249,7 +278,7 @@ namespace MareSynchronos.WebAPI
.Build(); .Build();
} }
private Task HeartbeatHubOnClosed(Exception? arg) private Task ConnectionHubOnClosed(Exception? arg)
{ {
CurrentUploads.Clear(); CurrentUploads.Clear();
CurrentDownloads.Clear(); CurrentDownloads.Clear();
@@ -259,16 +288,15 @@ namespace MareSynchronos.WebAPI
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task HeartbeatHubOnReconnected(string? arg) private Task ConnectionHubOnReconnected(string? arg)
{ {
Logger.Debug("Connection restored"); Logger.Debug("Connection restored");
OnlineUsers = _userHub!.InvokeAsync<int>(UserHubAPI.InvokeGetOnlineUsers).Result; _connectionDto = _connectionHub!.InvokeAsync<ConnectionDto>(ConnectionHubAPI.InvokeHeartbeat).Result;
_connectionDto = _heartbeatHub!.InvokeAsync<ConnectionDto>(ConnectionHubAPI.InvokeHeartbeat).Result;
Connected?.Invoke(); Connected?.Invoke();
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task HeartbeatHubOnReconnecting(Exception? arg) private Task ConnectionHubOnReconnecting(Exception? arg)
{ {
CurrentUploads.Clear(); CurrentUploads.Clear();
CurrentDownloads.Clear(); CurrentDownloads.Clear();
@@ -281,14 +309,14 @@ namespace MareSynchronos.WebAPI
private async Task StopAllConnections(CancellationToken token) private async Task StopAllConnections(CancellationToken token)
{ {
Logger.Verbose("Stopping all connections"); Logger.Verbose("Stopping all connections");
if (_heartbeatHub is not null) if (_connectionHub is not null)
{ {
await _heartbeatHub.StopAsync(token); await _connectionHub.StopAsync(token);
_heartbeatHub.Closed -= HeartbeatHubOnClosed; _connectionHub.Closed -= ConnectionHubOnClosed;
_heartbeatHub.Reconnected -= HeartbeatHubOnReconnected; _connectionHub.Reconnected -= ConnectionHubOnReconnected;
_heartbeatHub.Reconnecting += HeartbeatHubOnReconnecting; _connectionHub.Reconnecting += ConnectionHubOnReconnecting;
await _heartbeatHub.DisposeAsync(); await _connectionHub.DisposeAsync();
_heartbeatHub = null; _connectionHub = null;
} }
if (_fileHub is not null) if (_fileHub is not null)