From 7681c7ee668fa2bc35e97bd8357e3489549ce68b Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 20:53:48 +0200 Subject: [PATCH 01/10] Popup optimisation --- MareSynchronos/UI/CompactUI.cs | 3 ++- MareSynchronos/UI/GroupPanel.cs | 21 +++++++++++-------- MareSynchronos/UI/SettingsUi.cs | 30 ++++++++++++++++----------- MareSynchronos/UI/UIShared.cs | 36 +++++++++++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 21 deletions(-) diff --git a/MareSynchronos/UI/CompactUI.cs b/MareSynchronos/UI/CompactUI.cs index 5b1720a..c1f2db7 100644 --- a/MareSynchronos/UI/CompactUI.cs +++ b/MareSynchronos/UI/CompactUI.cs @@ -160,7 +160,7 @@ public class CompactUi : Window, IDisposable _lastAddedUserComment = string.Empty; } - if (ImGui.BeginPopupModal("Set Notes for New User", ref _showModalForUserAddition, ImGuiWindowFlags.AlwaysAutoResize)) + if (ImGui.BeginPopupModal("Set Notes for New User", ref _showModalForUserAddition, UiShared.PopupWindowFlags)) { if (_lastAddedUser == null) { @@ -180,6 +180,7 @@ public class CompactUi : Window, IDisposable _showModalForUserAddition = false; } } + UiShared.SetScaledWindowSize(275); ImGui.EndPopup(); } } diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 45e17e0..9100bab 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -95,11 +95,12 @@ namespace MareSynchronos.UI ? (userCanCreateMoreGroups ? "Create Syncshell" : $"You cannot create more than {_apiController.ServerInfo.MaxGroupsCreatedByUser} Syncshells") : (userCanJoinMoreGroups ? "Join Syncshell" + _syncShellToJoin : $"You cannot join more than {_apiController.ServerInfo.MaxGroupsJoinedByUser} Syncshells")); - if (ImGui.BeginPopupModal("Enter Syncshell Password", ref _showModalEnterPassword, ImGuiWindowFlags.AlwaysAutoResize)) + if (ImGui.BeginPopupModal("Enter Syncshell Password", ref _showModalEnterPassword, UiShared.PopupWindowFlags)) { UiShared.TextWrapped("Before joining any Syncshells please be aware that you will be automatically paired with everyone in the Syncshell."); ImGui.Separator(); UiShared.TextWrapped("Enter the password for Syncshell " + _syncShellToJoin + ":"); + ImGui.SetNextItemWidth(-1); ImGui.InputTextWithHint("##password", _syncShellToJoin + " Password", ref _syncShellPassword, 255, ImGuiInputTextFlags.Password); if (_errorGroupJoin) { @@ -119,12 +120,12 @@ namespace MareSynchronos.UI } _syncShellPassword = string.Empty; } + UiShared.SetScaledWindowSize(290); ImGui.EndPopup(); } - if (ImGui.BeginPopupModal("Create Syncshell", ref _showModalCreateGroup)) + if (ImGui.BeginPopupModal("Create Syncshell", ref _showModalCreateGroup, UiShared.PopupWindowFlags)) { - ImGui.SetWindowSize(new(400, 200)); UiShared.TextWrapped("Press the button below to create a new Syncshell."); ImGui.SetNextItemWidth(200); if (ImGui.Button("Create Syncshell")) @@ -145,6 +146,7 @@ namespace MareSynchronos.UI ImGui.Separator(); _errorGroupCreate = false; ImGui.TextUnformatted("Syncshell ID: " + _lastCreatedGroup.GID); + ImGui.AlignTextToFramePadding(); ImGui.TextUnformatted("Syncshell Password: " + _lastCreatedGroup.Password); ImGui.SameLine(); if (ImGuiComponents.IconButton(FontAwesomeIcon.Copy)) @@ -160,6 +162,7 @@ namespace MareSynchronos.UI new Vector4(1, 0, 0, 1)); } + UiShared.SetScaledWindowSize(350); ImGui.EndPopup(); } @@ -292,9 +295,8 @@ namespace MareSynchronos.UI if (!_showModalBanList) _modalBanListOpened = false; - if (ImGui.BeginPopupModal("Manage Banlist for " + group.GID, ref _showModalBanList)) + if (ImGui.BeginPopupModal("Manage Banlist for " + group.GID, ref _showModalBanList, UiShared.PopupWindowFlags)) { - ImGui.SetWindowSize(new Vector2(700, 300)); if (UiShared.IconTextButton(FontAwesomeIcon.Retweet, "Refresh Banlist from Server")) { _bannedUsers = _apiController.GetBannedUsersForGroup(group.GID).Result; @@ -331,6 +333,7 @@ namespace MareSynchronos.UI ImGui.EndTable(); } + UiShared.SetScaledWindowSize(700, 300); ImGui.EndPopup(); } @@ -343,10 +346,11 @@ namespace MareSynchronos.UI if (!_showModalChangePassword) _modalChangePwOpened = false; - if (ImGui.BeginPopupModal("Change Syncshell Password", ref _showModalChangePassword, ImGuiWindowFlags.AlwaysAutoResize)) + if (ImGui.BeginPopupModal("Change Syncshell Password", ref _showModalChangePassword, UiShared.PopupWindowFlags)) { UiShared.TextWrapped("Enter the new Syncshell password for Syncshell " + name + " here."); UiShared.TextWrapped("This action is irreversible"); + ImGui.SetNextItemWidth(-1); ImGui.InputTextWithHint("##changepw", "New password for " + name, ref _newSyncShellPassword, 255); if (ImGui.Button("Change password")) { @@ -361,6 +365,7 @@ namespace MareSynchronos.UI UiShared.ColorTextWrapped("The selected password is too short. It must be at least 10 characters.", new Vector4(1, 0, 0, 1)); } + UiShared.SetScaledWindowSize(290); ImGui.EndPopup(); } @@ -707,9 +712,8 @@ namespace MareSynchronos.UI if (!_showModalBanUser) _banUserPopupOpen = false; - if (ImGui.BeginPopupModal("Ban User", ref _showModalBanUser)) + if (ImGui.BeginPopupModal("Ban User", ref _showModalBanUser, UiShared.PopupWindowFlags)) { - ImGui.SetWindowSize(new Vector2(300, 200)); UiShared.TextWrapped("User " + (entry.UserAlias ?? entry.UserUID) + " will be banned and removed from this Syncshell."); ImGui.InputTextWithHint("##banreason", "Ban Reason", ref _banReason, 255); if (ImGui.Button("Ban User")) @@ -720,6 +724,7 @@ namespace MareSynchronos.UI _banReason = string.Empty; } UiShared.TextWrapped("The reason will be displayed in the banlist. The current server-side alias if present (Vanity ID) will automatically be attached to the reason."); + UiShared.SetScaledWindowSize(300); ImGui.EndPopup(); } } diff --git a/MareSynchronos/UI/SettingsUi.cs b/MareSynchronos/UI/SettingsUi.cs index cbfb3ab..53958aa 100644 --- a/MareSynchronos/UI/SettingsUi.cs +++ b/MareSynchronos/UI/SettingsUi.cs @@ -431,28 +431,31 @@ public class SettingsUi : Window, IDisposable UiShared.DrawHelpText("Completely deletes all your uploaded files on the service."); - if (ImGui.BeginPopupModal("Delete all your files?", ref _deleteFilesPopupModalShown, - ImGuiWindowFlags.AlwaysAutoResize)) + if (ImGui.BeginPopupModal("Delete all your files?", ref _deleteFilesPopupModalShown, UiShared.PopupWindowFlags)) { UiShared.TextWrapped( "All your own uploaded files on the service will be deleted.\nThis operation cannot be undone."); ImGui.Text("Are you sure you want to continue?"); ImGui.Separator(); - if (ImGui.Button("Delete everything", new Vector2(150, 0))) + ImGui.Spacing(); + + var buttonSize = (ImGui.GetWindowContentRegionMax().X - ImGui.GetWindowContentRegionMin().X - + ImGui.GetStyle().ItemSpacing.X) / 2; + + if (ImGui.Button("Delete everything", new Vector2(buttonSize, 0))) { Task.Run(() => _apiController.DeleteAllMyFiles()); - ImGui.CloseCurrentPopup(); _deleteFilesPopupModalShown = false; } ImGui.SameLine(); - if (ImGui.Button("Cancel##cancelDelete", new Vector2(150, 0))) + if (ImGui.Button("Cancel##cancelDelete", new Vector2(buttonSize, 0))) { - ImGui.CloseCurrentPopup(); _deleteFilesPopupModalShown = false; } + UiShared.SetScaledWindowSize(325); ImGui.EndPopup(); } @@ -464,30 +467,33 @@ public class SettingsUi : Window, IDisposable UiShared.DrawHelpText("Completely deletes your account and all uploaded files to the service."); - if (ImGui.BeginPopupModal("Delete your account?", ref _deleteAccountPopupModalShown, - ImGuiWindowFlags.AlwaysAutoResize)) + if (ImGui.BeginPopupModal("Delete your account?", ref _deleteAccountPopupModalShown, UiShared.PopupWindowFlags)) { UiShared.TextWrapped( "Your account and all associated files and data on the service will be deleted."); UiShared.TextWrapped("Your UID will be removed from all pairing lists."); ImGui.Text("Are you sure you want to continue?"); ImGui.Separator(); - if (ImGui.Button("Delete account", new Vector2(150, 0))) + ImGui.Spacing(); + + var buttonSize = (ImGui.GetWindowContentRegionMax().X - ImGui.GetWindowContentRegionMin().X - + ImGui.GetStyle().ItemSpacing.X) / 2; + + if (ImGui.Button("Delete account", new Vector2(buttonSize, 0))) { Task.Run(() => _apiController.DeleteAccount()); - ImGui.CloseCurrentPopup(); _deleteAccountPopupModalShown = false; SwitchToIntroUi?.Invoke(); } ImGui.SameLine(); - if (ImGui.Button("Cancel##cancelDelete", new Vector2(150, 0))) + if (ImGui.Button("Cancel##cancelDelete", new Vector2(buttonSize, 0))) { - ImGui.CloseCurrentPopup(); _deleteAccountPopupModalShown = false; } + UiShared.SetScaledWindowSize(325); ImGui.EndPopup(); } } diff --git a/MareSynchronos/UI/UIShared.cs b/MareSynchronos/UI/UIShared.cs index 3940aba..0705075 100644 --- a/MareSynchronos/UI/UIShared.cs +++ b/MareSynchronos/UI/UIShared.cs @@ -41,6 +41,10 @@ public class UiShared : IDisposable public bool UidFontBuilt { get; private set; } public static bool CtrlPressed() => (GetKeyState(0xA2) & 0x8000) != 0 || (GetKeyState(0xA3) & 0x8000) != 0; public static bool ShiftPressed() => (GetKeyState(0xA1) & 0x8000) != 0 || (GetKeyState(0xA0) & 0x8000) != 0; + + public static ImGuiWindowFlags PopupWindowFlags = ImGuiWindowFlags.NoResize | + ImGuiWindowFlags.NoScrollbar | + ImGuiWindowFlags.NoScrollWithMouse; public ApiController ApiController => _apiController; @@ -98,6 +102,38 @@ public class UiShared : IDisposable } } + public static void SetScaledWindowSize(float width, bool centerWindow = true) + { + var newLineHeight = ImGui.GetCursorPosY(); + ImGui.NewLine(); + newLineHeight = ImGui.GetCursorPosY() - newLineHeight; + var x = width * ImGuiHelpers.GlobalScale; + var y = ImGui.GetCursorPos().Y + ImGui.GetWindowContentRegionMin().Y - newLineHeight * 2 - ImGui.GetStyle().ItemSpacing.Y; + + if (centerWindow) + { + var center = ImGui.GetMainViewport().GetCenter(); + ImGui.SetWindowPos(new Vector2(center.X - x / 2, center.Y - y / 2)); + } + + ImGui.SetWindowSize(new Vector2(x, y)); + } + + public static void SetScaledWindowSize(float width, float height, bool centerWindow = true) + { + ImGui.SameLine(); + var x = width * ImGuiHelpers.GlobalScale; + var y = height * ImGuiHelpers.GlobalScale; + + if (centerWindow) + { + var center = ImGui.GetMainViewport().GetCenter(); + ImGui.SetWindowPos(new Vector2(center.X - x / 2, center.Y - y / 2)); + } + + ImGui.SetWindowSize(new Vector2(x, y)); + } + public static void DrawWithID(string id, Action drawSubSection) { ImGui.PushID(id); From 82d6ad782d28ae90c0729ce1912ed2eabf0e1107 Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 20:56:12 +0200 Subject: [PATCH 02/10] Table fixed. Multiple entries are now displayed correctly --- MareSynchronos/UI/GroupPanel.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 9100bab..5d28c4d 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -302,7 +302,7 @@ namespace MareSynchronos.UI _bannedUsers = _apiController.GetBannedUsersForGroup(group.GID).Result; } - if (ImGui.BeginTable("bannedusertable" + group.GID, 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp)) + if (ImGui.BeginTable("bannedusertable" + group.GID, 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.ScrollY)) { ImGui.TableSetupColumn("UID", ImGuiTableColumnFlags.None, 1); ImGui.TableSetupColumn("By", ImGuiTableColumnFlags.None, 1); @@ -328,7 +328,6 @@ namespace MareSynchronos.UI _ = _apiController.UnbanUserFromGroup(group.GID, bannedUser.UID); _bannedUsers.RemoveAll(b => string.Equals(b.UID, bannedUser.UID, StringComparison.Ordinal)); } - ImGui.TableNextColumn(); } ImGui.EndTable(); From a20e720cbb157692f2314d890174ea4c99b33bdb Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 20:57:27 +0200 Subject: [PATCH 03/10] Lock icon centred --- MareSynchronos/UI/GroupPanel.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 5d28c4d..08baab6 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -398,15 +398,17 @@ namespace MareSynchronos.UI bool invitesEnabled = entry.InvitesEnabled ?? true; var lockedIcon = invitesEnabled ? FontAwesomeIcon.LockOpen : FontAwesomeIcon.Lock; var iconSize = UiShared.GetIconSize(lockedIcon); + var diffLockUnlockIcons = invitesEnabled ? 0 : (UiShared.GetIconSize(FontAwesomeIcon.LockOpen).X - iconSize.X) / 2; var barbuttonSize = UiShared.GetIconButtonSize(FontAwesomeIcon.Bars); var isOwner = string.Equals(entry.OwnedBy, _apiController.UID, StringComparison.Ordinal); - ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - barbuttonSize.X - iconSize.X - ImGui.GetStyle().ItemSpacing.X); + ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - barbuttonSize.X - iconSize.X - diffLockUnlockIcons - ImGui.GetStyle().ItemSpacing.X); ImGui.PushFont(UiBuilder.IconFont); ImGui.Text(lockedIcon.ToIconString()); ImGui.PopFont(); UiShared.AttachToolTip(invitesEnabled ? "Syncshell is open for new joiners" : "Syncshell is closed for new joiners"); ImGui.SameLine(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + diffLockUnlockIcons); if (ImGuiComponents.IconButton(FontAwesomeIcon.Bars)) { ImGui.OpenPopup("ShellPopup"); From b776f754f0c109c43ac74ce34e508697f9b05161 Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 20:58:40 +0200 Subject: [PATCH 04/10] Displaying the correct icon to match the text --- MareSynchronos/UI/GroupPanel.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 08baab6..88cb481 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -446,7 +446,8 @@ namespace MareSynchronos.UI if (isOwner) { - if (UiShared.IconTextButton(lockedIcon, invitesEnabled ? "Lock Syncshell" : "Unlock Syncshell")) + var changedToIcon = !invitesEnabled ? FontAwesomeIcon.LockOpen : FontAwesomeIcon.Lock; + if (UiShared.IconTextButton(changedToIcon, invitesEnabled ? "Lock Syncshell" : "Unlock Syncshell")) { ImGui.CloseCurrentPopup(); _ = _apiController.SendGroupChangeInviteState(entry.GID, !entry.InvitesEnabled ?? true); From 7ae308fd4e20e0ae970bebab399c73a045130663 Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 21:01:41 +0200 Subject: [PATCH 05/10] Plus button + bar button are now correctly shown for moderators --- MareSynchronos/UI/GroupPanel.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 88cb481..231b2af 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -629,7 +629,10 @@ namespace MareSynchronos.UI if (plusButtonShown) { ImGui.SetCursorPosY(originalY); - ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - plusButtonSize.X - (isOwner ? barButtonSize.X + ImGui.GetStyle().ItemSpacing.X : 0)); + var barWidth = isOwner || (isModerator && !userIsMod && !userIsOwner) + ? barButtonSize.X + ImGui.GetStyle().ItemSpacing.X + : 0; + ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - plusButtonSize.X - barWidth); if (ImGuiComponents.IconButton(FontAwesomeIcon.Plus)) { @@ -641,7 +644,6 @@ namespace MareSynchronos.UI if (isOwner || (isModerator && !userIsMod && !userIsOwner)) { ImGui.SetCursorPosY(originalY); - var subtractedWidth = plusButtonShown ? (plusButtonSize.X) : 0; ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - barButtonSize.X); if (ImGuiComponents.IconButton(FontAwesomeIcon.Bars)) From ae44599db033215fa625c601ef4bb57ad4a6bf34 Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 21:02:51 +0200 Subject: [PATCH 06/10] Rows without buttons were smaller than rows with buttons --- MareSynchronos/UI/GroupPanel.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 231b2af..5323b12 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -708,6 +708,12 @@ namespace MareSynchronos.UI ImGui.EndPopup(); } + if (!plusButtonShown && !(isOwner || (isModerator && !userIsMod && !userIsOwner))) + { + ImGui.SameLine(); + ImGui.Dummy(barButtonSize with { X = 0 }); + } + if (_showModalBanUser && !_banUserPopupOpen) { ImGui.OpenPopup("Ban User"); From 3efd198c6c8556e8497933b66b8418a3cfd27e0f Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 21:04:33 +0200 Subject: [PATCH 07/10] Child removed to be able to display buttons with icon and text also in tables --- MareSynchronos/UI/UIShared.cs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/MareSynchronos/UI/UIShared.cs b/MareSynchronos/UI/UIShared.cs index 0705075..341e35e 100644 --- a/MareSynchronos/UI/UIShared.cs +++ b/MareSynchronos/UI/UIShared.cs @@ -605,23 +605,19 @@ public class UiShared : IDisposable var buttonSizeY = (iconSize.Y > textSize.Y ? iconSize.Y : textSize.Y) + padding.Y * 2; var buttonSize = new Vector2(buttonSizeX, buttonSizeY); - if (ImGui.BeginChild(icon.ToIconString() + text, buttonSize)) + if (ImGui.Button("###" + icon.ToIconString() + text, buttonSize)) { - if (ImGui.Button("", buttonSize)) - { - buttonClicked = true; - } - - ImGui.SameLine(); - ImGui.SetCursorPosX(padding.X); - ImGui.PushFont(UiBuilder.IconFont); - ImGui.Text(icon.ToIconString()); - ImGui.PopFont(); - ImGui.SameLine(); - ImGui.Text(text); - ImGui.EndChild(); + buttonClicked = true; } + ImGui.SameLine(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() - buttonSize.X - padding.X); + ImGui.PushFont(UiBuilder.IconFont); + ImGui.Text(icon.ToIconString()); + ImGui.PopFont(); + ImGui.SameLine(); + ImGui.Text(text); + return buttonClicked; } From 10990eba37ca937988d77c4b35dca8c0f15e1614 Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 22:09:30 +0200 Subject: [PATCH 08/10] Connect button centred --- MareSynchronos/UI/CompactUI.cs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/MareSynchronos/UI/CompactUI.cs b/MareSynchronos/UI/CompactUI.cs index c1f2db7..3f765d7 100644 --- a/MareSynchronos/UI/CompactUI.cs +++ b/MareSynchronos/UI/CompactUI.cs @@ -478,14 +478,15 @@ public class CompactUi : Window, IDisposable string shardConnection = string.Equals(_apiController.ServerInfo.ShardName, "Main", StringComparison.OrdinalIgnoreCase) ? string.Empty : $"Shard: {_apiController.ServerInfo.ShardName}"; #endif var shardTextSize = ImGui.CalcTextSize(shardConnection); + var printShard = !string.IsNullOrEmpty(_apiController.ServerInfo.ShardName) && shardConnection != string.Empty; if (_apiController.ServerState is ServerState.Connected) { - ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - buttonSize.X) / 2 - (userSize.X + textSize.X) / 2); - ImGui.AlignTextToFramePadding(); + ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - buttonSize.X) / 2 - (userSize.X + textSize.X) / 2 - ImGui.GetStyle().ItemSpacing.X / 2); + if (!printShard) ImGui.AlignTextToFramePadding(); ImGui.TextColored(ImGuiColors.ParsedGreen, userCount); ImGui.SameLine(); - ImGui.AlignTextToFramePadding(); + if (!printShard) ImGui.AlignTextToFramePadding(); ImGui.Text("Users Online"); } else @@ -493,8 +494,19 @@ public class CompactUi : Window, IDisposable ImGui.AlignTextToFramePadding(); ImGui.TextColored(ImGuiColors.DalamudRed, "Not connected to any server"); } + + if (printShard) + { + ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetStyle().ItemSpacing.Y); + ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - buttonSize.X) / 2 - shardTextSize.X / 2); + ImGui.TextUnformatted(shardConnection); + } ImGui.SameLine(ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth() - buttonSize.X); + if (printShard) + { + ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ((userSize.Y + textSize.Y) / 2 + shardTextSize.Y) / 2 - ImGui.GetStyle().ItemSpacing.Y + buttonSize.Y / 2); + } var color = UiShared.GetBoolColor(!_configuration.FullPause); var connectedIcon = !_configuration.FullPause ? FontAwesomeIcon.Link : FontAwesomeIcon.Unlink; @@ -507,12 +519,6 @@ public class CompactUi : Window, IDisposable } ImGui.PopStyleColor(); UiShared.AttachToolTip(!_configuration.FullPause ? "Disconnect from " + _apiController.ServerDictionary[_configuration.ApiUri] : "Connect to " + _apiController.ServerDictionary[_configuration.ApiUri]); - - if (!string.IsNullOrEmpty(_apiController.ServerInfo.ShardName)) - { - ImGui.SetCursorPosX((ImGui.GetWindowContentRegionMin().X + UiShared.GetWindowContentRegionWidth()) / 2 - shardTextSize.X / 2); - ImGui.TextUnformatted(shardConnection); - } } private void DrawTransfers() From b659672085f0607f6d2148e9df3678bc237565c2 Mon Sep 17 00:00:00 2001 From: xPumaa <35280763+xPumaa@users.noreply.github.com> Date: Fri, 7 Oct 2022 22:16:27 +0200 Subject: [PATCH 09/10] Getting the ban list when opening the popup --- MareSynchronos/UI/GroupPanel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index 5323b12..a51ec51 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -478,7 +478,7 @@ namespace MareSynchronos.UI { ImGui.CloseCurrentPopup(); _showModalBanList = true; - _bannedUsers = new(); + _bannedUsers = _apiController.GetBannedUsersForGroup(entry.GID).Result; } if (isOwner) From f9cf26ed6940cd29e5e2ed9d821cc41fba6115ac Mon Sep 17 00:00:00 2001 From: rootdarkarchon Date: Sat, 8 Oct 2022 14:35:30 +0200 Subject: [PATCH 10/10] migrate to strong api calls (#29) * migrate to strong api calls * set last added user to null on changing notes popup setting --- MareAPI | 2 +- .../Managers/OnlinePlayerManager.cs | 2 +- MareSynchronos/UI/CompactUI.cs | 8 +- MareSynchronos/UI/GroupPanel.cs | 32 +-- MareSynchronos/UI/SettingsUi.cs | 23 +- .../WebAPI/ApIController.Functions.Files.cs | 46 +++- .../WebAPI/ApIController.Functions.Users.cs | 36 +-- .../WebAPI/ApiController.Functions.Admin.cs | 36 +-- .../ApiController.Functions.Callbacks.cs | 212 +++++++++++++----- .../WebAPI/ApiController.Functions.Groups.cs | 69 +++--- MareSynchronos/WebAPI/ApiController.cs | 73 +++--- 11 files changed, 338 insertions(+), 201 deletions(-) diff --git a/MareAPI b/MareAPI index 1c3327f..5db43c8 160000 --- a/MareAPI +++ b/MareAPI @@ -1 +1 @@ -Subproject commit 1c3327f9bc9e42d2d75886a01f72655c2c6fb0f3 +Subproject commit 5db43c8e7acf98fe8e9b925d0ae028e42e9c8a04 diff --git a/MareSynchronos/Managers/OnlinePlayerManager.cs b/MareSynchronos/Managers/OnlinePlayerManager.cs index 20a683c..2901d41 100644 --- a/MareSynchronos/Managers/OnlinePlayerManager.cs +++ b/MareSynchronos/Managers/OnlinePlayerManager.cs @@ -79,7 +79,7 @@ public class OnlinePlayerManager : IDisposable private void ApiControllerOnConnected() { - var apiTask = _apiController.GetOnlineCharacters(); + var apiTask = _apiController.UserGetOnlineCharacters(); Task.WaitAll(apiTask); diff --git a/MareSynchronos/UI/CompactUI.cs b/MareSynchronos/UI/CompactUI.cs index 3f765d7..2a460e2 100644 --- a/MareSynchronos/UI/CompactUI.cs +++ b/MareSynchronos/UI/CompactUI.cs @@ -201,7 +201,7 @@ public class CompactUi : Window, IDisposable { if (_apiController.PairedClients.All(w => !string.Equals(w.OtherUID, _pairToAdd, StringComparison.Ordinal))) { - _ = _apiController.SendPairedClientAddition(_pairToAdd); + _ = _apiController.UserAddPair(_pairToAdd); _pairToAdd = string.Empty; } } @@ -279,7 +279,7 @@ public class CompactUi : Window, IDisposable Logger.Debug(users.Count.ToString()); foreach (var entry in users) { - _ = _apiController.SendPairedClientPauseChange(entry.OtherUID, !entry.IsPaused); + _ = _apiController.UserChangePairPauseStatus(entry.OtherUID, !entry.IsPaused); } _timeout.Start(); @@ -407,7 +407,7 @@ public class CompactUi : Window, IDisposable { if (UiShared.CtrlPressed()) { - _ = _apiController.SendPairedClientRemoval(entry.OtherUID); + _ = _apiController.UserRemovePair(entry.OtherUID); } } UiShared.AttachToolTip("Hold CTRL and click to unpair permanently from " + entryUID); @@ -418,7 +418,7 @@ public class CompactUi : Window, IDisposable ImGui.SetCursorPosY(originalY); if (ImGuiComponents.IconButton(pauseIcon)) { - _ = _apiController.SendPairedClientPauseChange(entry.OtherUID, !entry.IsPaused); + _ = _apiController.UserChangePairPauseStatus(entry.OtherUID, !entry.IsPaused); } UiShared.AttachToolTip(!entry.IsPaused ? "Pause pairing with " + entryUID diff --git a/MareSynchronos/UI/GroupPanel.cs b/MareSynchronos/UI/GroupPanel.cs index a51ec51..2d3b549 100644 --- a/MareSynchronos/UI/GroupPanel.cs +++ b/MareSynchronos/UI/GroupPanel.cs @@ -112,7 +112,7 @@ namespace MareSynchronos.UI { var shell = _syncShellToJoin; var pw = _syncShellPassword; - _errorGroupJoin = !_apiController.SendGroupJoin(shell, pw).Result; + _errorGroupJoin = !_apiController.GroupJoin(shell, pw).Result; if (!_errorGroupJoin) { _syncShellToJoin = string.Empty; @@ -132,7 +132,7 @@ namespace MareSynchronos.UI { try { - _lastCreatedGroup = _apiController.CreateGroup().Result; + _lastCreatedGroup = _apiController.GroupCreate().Result; } catch { @@ -204,7 +204,7 @@ namespace MareSynchronos.UI var pauseIcon = (group.IsPaused ?? false) ? FontAwesomeIcon.Play : FontAwesomeIcon.Pause; if (ImGuiComponents.IconButton(pauseIcon)) { - _ = _apiController.SendPauseGroup(group.GID, !group.IsPaused ?? false); + _ = _apiController.GroupChangePauseState(group.GID, !group.IsPaused ?? false); } UiShared.AttachToolTip(((group.IsPaused ?? false) ? "Resume" : "Pause") + " pairing with all users in this Syncshell"); ImGui.SameLine(); @@ -299,7 +299,7 @@ namespace MareSynchronos.UI { if (UiShared.IconTextButton(FontAwesomeIcon.Retweet, "Refresh Banlist from Server")) { - _bannedUsers = _apiController.GetBannedUsersForGroup(group.GID).Result; + _bannedUsers = _apiController.GroupGetBannedUsers(group.GID).Result; } if (ImGui.BeginTable("bannedusertable" + group.GID, 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.ScrollY)) @@ -325,7 +325,7 @@ namespace MareSynchronos.UI ImGui.TableNextColumn(); if (UiShared.IconTextButton(FontAwesomeIcon.Check, "Unban")) { - _ = _apiController.UnbanUserFromGroup(group.GID, bannedUser.UID); + _ = _apiController.GroupUnbanUser(group.GID, bannedUser.UID); _bannedUsers.RemoveAll(b => string.Equals(b.UID, bannedUser.UID, StringComparison.Ordinal)); } } @@ -354,7 +354,7 @@ namespace MareSynchronos.UI if (ImGui.Button("Change password")) { var pw = _newSyncShellPassword; - _isPasswordValid = _apiController.ChangeGroupPassword(group.GID, pw).Result; + _isPasswordValid = _apiController.GroupChangePassword(group.GID, pw).Result; _newSyncShellPassword = string.Empty; if (_isPasswordValid) _showModalChangePassword = false; } @@ -420,7 +420,7 @@ namespace MareSynchronos.UI { if (UiShared.CtrlPressed()) { - _ = _apiController.SendLeaveGroup(entry.GID); + _ = _apiController.GroupLeave(entry.GID); } } UiShared.AttachToolTip("Hold CTRL and click to leave this Syncshell" + (!string.Equals(entry.OwnedBy, _apiController.UID, StringComparison.Ordinal) ? string.Empty : Environment.NewLine @@ -450,7 +450,7 @@ namespace MareSynchronos.UI if (UiShared.IconTextButton(changedToIcon, invitesEnabled ? "Lock Syncshell" : "Unlock Syncshell")) { ImGui.CloseCurrentPopup(); - _ = _apiController.SendGroupChangeInviteState(entry.GID, !entry.InvitesEnabled ?? true); + _ = _apiController.GroupChangeInviteState(entry.GID, !entry.InvitesEnabled ?? true); } UiShared.AttachToolTip("Change Syncshell joining permissions" + Environment.NewLine + "Syncshell is currently " + (invitesEnabled ? "open" : "closed") + " for people to join"); @@ -468,7 +468,7 @@ namespace MareSynchronos.UI if (UiShared.CtrlPressed()) { ImGui.CloseCurrentPopup(); - _ = _apiController.SendClearGroup(entry.GID); + _ = _apiController.GroupClear(entry.GID); } } UiShared.AttachToolTip("Hold CTRL and click to clear this Syncshell." + Environment.NewLine + "WARNING: this action is irreversible." + Environment.NewLine @@ -488,7 +488,7 @@ namespace MareSynchronos.UI if (UiShared.CtrlPressed() && UiShared.ShiftPressed()) { ImGui.CloseCurrentPopup(); - _ = _apiController.SendDeleteGroup(entry.GID); + _ = _apiController.GroupDelete(entry.GID); } } UiShared.AttachToolTip("Hold CTRL and Shift and click to delete this Syncshell." + Environment.NewLine + "WARNING: this action is irreversible."); @@ -636,7 +636,7 @@ namespace MareSynchronos.UI if (ImGuiComponents.IconButton(FontAwesomeIcon.Plus)) { - _ = _apiController.SendPairedClientAddition(entry.UserUID); + _ = _apiController.UserAddPair(entry.UserUID); } UiShared.AttachToolTip("Pair with " + entryUID + " individually"); } @@ -660,7 +660,7 @@ namespace MareSynchronos.UI if (UiShared.IconTextButton(FontAwesomeIcon.Thumbtack, pinText)) { ImGui.CloseCurrentPopup(); - _ = _apiController.SendChangeUserPinned(entry.GroupGID, entry.UserUID, !entry.IsPinned ?? false); + _ = _apiController.GroupChangePinned(entry.GroupGID, entry.UserUID, !entry.IsPinned ?? false); } UiShared.AttachToolTip("Pin this user to the Syncshell. Pinned users will not be deleted in case of a manually initiated Syncshell clean"); @@ -669,7 +669,7 @@ namespace MareSynchronos.UI if (UiShared.CtrlPressed()) { ImGui.CloseCurrentPopup(); - _ = _apiController.SendRemoveUserFromGroup(entry.GroupGID, entry.UserUID); + _ = _apiController.GroupRemoveUser(entry.GroupGID, entry.UserUID); } } @@ -690,7 +690,7 @@ namespace MareSynchronos.UI if (UiShared.CtrlPressed()) { ImGui.CloseCurrentPopup(); - _ = _apiController.SetModeratorForGroup(entry.GroupGID, entry.UserUID, !entry.IsModerator ?? false); + _ = _apiController.GroupSetModerator(entry.GroupGID, entry.UserUID, !entry.IsModerator ?? false); } } UiShared.AttachToolTip("Hold CTRL to change the moderator status for " + (entry.UserAlias ?? entry.UserUID) + Environment.NewLine + @@ -700,7 +700,7 @@ namespace MareSynchronos.UI if (UiShared.CtrlPressed() && UiShared.ShiftPressed()) { ImGui.CloseCurrentPopup(); - _ = _apiController.ChangeOwnerOfGroup(entry.GroupGID, entry.UserUID); + _ = _apiController.GroupChangeOwnership(entry.GroupGID, entry.UserUID); } } UiShared.AttachToolTip("Hold CTRL and SHIFT and click to transfer ownership of this Syncshell to " + (entry.UserAlias ?? entry.UserUID) + Environment.NewLine + "WARNING: This action is irreversible."); @@ -730,7 +730,7 @@ namespace MareSynchronos.UI { ImGui.CloseCurrentPopup(); var reason = _banReason; - _ = _apiController.BanUserFromGroup(entry.GroupGID, entry.UserUID, reason); + _ = _apiController.GroupBanUser(entry.GroupGID, entry.UserUID, reason); _banReason = string.Empty; } UiShared.TextWrapped("The reason will be displayed in the banlist. The current server-side alias if present (Vanity ID) will automatically be attached to the reason."); diff --git a/MareSynchronos/UI/SettingsUi.cs b/MareSynchronos/UI/SettingsUi.cs index 53958aa..69f8f06 100644 --- a/MareSynchronos/UI/SettingsUi.cs +++ b/MareSynchronos/UI/SettingsUi.cs @@ -158,6 +158,7 @@ public class SettingsUi : Window, IDisposable ImGui.Separator(); if (ImGui.Checkbox("Open Notes Popup on user addition", ref _openPopupOnAddition)) { + _apiController.LastAddedUser = null; _configuration.OpenPopupOnAdd = _openPopupOnAddition; _configuration.Save(); } @@ -196,14 +197,14 @@ public class SettingsUi : Window, IDisposable if (ImGui.Button( FontAwesomeIcon.Upload.ToIconString() + "##updateFile" + forbiddenFile.Hash)) { - _ = _apiController.AddOrUpdateForbiddenFileEntry(forbiddenFile); + _ = _apiController.AdminUpdateOrAddForbiddenFile(forbiddenFile); } ImGui.SameLine(); if (ImGui.Button(FontAwesomeIcon.Trash.ToIconString() + "##deleteFile" + forbiddenFile.Hash)) { - _ = _apiController.DeleteForbiddenFileEntry(forbiddenFile); + _ = _apiController.AdminDeleteForbiddenFile(forbiddenFile); } ImGui.PopFont(); @@ -221,7 +222,7 @@ public class SettingsUi : Window, IDisposable ImGui.PushFont(UiBuilder.IconFont); if (ImGui.Button(FontAwesomeIcon.Plus.ToIconString() + "##addForbiddenFile")) { - _ = _apiController.AddOrUpdateForbiddenFileEntry(new ForbiddenFileDto() + _ = _apiController.AdminUpdateOrAddForbiddenFile(new ForbiddenFileDto() { ForbiddenBy = _forbiddenFileHashForbiddenBy, Hash = _forbiddenFileHashEntry @@ -271,7 +272,7 @@ public class SettingsUi : Window, IDisposable if (ImGui.Button(FontAwesomeIcon.Upload.ToIconString() + "##updateUser" + bannedUser.CharacterHash)) { - _ = _apiController.AddOrUpdateBannedUserEntry(bannedUser); + _ = _apiController.AdminUpdateOrAddBannedUser(bannedUser); } ImGui.SameLine(); @@ -280,7 +281,7 @@ public class SettingsUi : Window, IDisposable if (ImGui.Button(FontAwesomeIcon.Trash.ToIconString() + "##deleteUser" + bannedUser.CharacterHash)) { - _ = _apiController.DeleteBannedUserEntry(bannedUser); + _ = _apiController.AdminDeleteBannedUser(bannedUser); } ImGui.PopFont(); @@ -305,7 +306,7 @@ public class SettingsUi : Window, IDisposable ImGui.PushFont(UiBuilder.IconFont); if (ImGui.Button(FontAwesomeIcon.Plus.ToIconString() + "##addForbiddenFile")) { - _ = _apiController.AddOrUpdateBannedUserEntry(new BannedUserDto() + _ = _apiController.AdminUpdateOrAddBannedUser(new BannedUserDto() { CharacterHash = _forbiddenFileHashForbiddenBy, Reason = _forbiddenFileHashEntry @@ -378,7 +379,7 @@ public class SettingsUi : Window, IDisposable if (ImGui.Button(FontAwesomeIcon.SkullCrossbones.ToIconString() + "##onlineUserBan" + onlineUser.CharacterNameHash)) { - _ = _apiController.AddOrUpdateBannedUserEntry(new BannedUserDto + _ = _apiController.AdminUpdateOrAddBannedUser(new BannedUserDto { CharacterHash = onlineUser.CharacterNameHash, Reason = "Banned by " + _uiShared.PlayerName @@ -393,7 +394,7 @@ public class SettingsUi : Window, IDisposable "##onlineUserModerator" + onlineUser.CharacterNameHash)) { - _apiController.PromoteToModerator(onlineUser.UID); + _apiController.AdminChangeModeratorStatus(onlineUser.UID, true); } } else @@ -402,7 +403,7 @@ public class SettingsUi : Window, IDisposable "##onlineUserNonModerator" + onlineUser.CharacterNameHash)) { - _apiController.DemoteFromModerator(onlineUser.UID); + _apiController.AdminChangeModeratorStatus(onlineUser.UID, false); } } } @@ -444,7 +445,7 @@ public class SettingsUi : Window, IDisposable if (ImGui.Button("Delete everything", new Vector2(buttonSize, 0))) { - Task.Run(() => _apiController.DeleteAllMyFiles()); + Task.Run(() => _apiController.FilesDeleteAll()); _deleteFilesPopupModalShown = false; } @@ -481,7 +482,7 @@ public class SettingsUi : Window, IDisposable if (ImGui.Button("Delete account", new Vector2(buttonSize, 0))) { - Task.Run(() => _apiController.DeleteAccount()); + Task.Run(() => _apiController.UserDelete()); _deleteAccountPopupModalShown = false; SwitchToIntroUi?.Invoke(); } diff --git a/MareSynchronos/WebAPI/ApIController.Functions.Files.cs b/MareSynchronos/WebAPI/ApIController.Functions.Files.cs index 89727b4..d077bdd 100644 --- a/MareSynchronos/WebAPI/ApIController.Functions.Files.cs +++ b/MareSynchronos/WebAPI/ApIController.Functions.Files.cs @@ -20,20 +20,25 @@ public partial class ApiController private readonly HashSet _verifiedUploadedHashes; private int _downloadId = 0; - public void CancelUpload() + public async void CancelUpload() { if (_uploadCancellationTokenSource != null) { Logger.Debug("Cancelling upload"); _uploadCancellationTokenSource?.Cancel(); - _mareHub!.SendAsync(Api.SendFileAbortUpload); CurrentUploads.Clear(); + await FilesAbortUpload().ConfigureAwait(false); } } - public async Task DeleteAllMyFiles() + public async Task FilesAbortUpload() { - await _mareHub!.SendAsync(Api.SendFileDeleteAllFiles).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(FilesAbortUpload)).ConfigureAwait(false); + } + + public async Task FilesDeleteAll() + { + await _mareHub!.SendAsync(nameof(FilesDeleteAll)).ConfigureAwait(false); } private async Task DownloadFile(int downloadId, string hash, Uri downloadUri, CancellationToken ct) @@ -95,7 +100,7 @@ public partial class ApiController Logger.Debug("Downloading files (Download ID " + currentDownloadId + ")"); List downloadFileInfoFromService = new(); - downloadFileInfoFromService.AddRange(await _mareHub!.InvokeAsync>(Api.InvokeGetFilesSizes, fileReplacementDto.Select(f => f.Hash).ToList(), ct).ConfigureAwait(false)); + downloadFileInfoFromService.AddRange(await FilesGetSizes(fileReplacementDto.Select(f => f.Hash).ToList()).ConfigureAwait(false)); Logger.Debug("Files with size 0 or less: " + string.Join(", ", downloadFileInfoFromService.Where(f => f.Size <= 0).Select(f => f.Hash))); @@ -183,7 +188,7 @@ public partial class ApiController if (unverifiedUploadHashes.Any()) { Logger.Debug("Verifying " + unverifiedUploadHashes.Count + " files"); - var filesToUpload = await _mareHub!.InvokeAsync>(Api.InvokeFileSendFiles, unverifiedUploadHashes, uploadToken).ConfigureAwait(false); + var filesToUpload = await FilesSend(unverifiedUploadHashes).ConfigureAwait(false); foreach (var file in filesToUpload.Where(f => !f.IsForbidden)) { @@ -233,11 +238,11 @@ public partial class ApiController } Logger.Debug("Upload tasks complete, waiting for server to confirm"); - var anyUploadsOpen = await _mareHub!.InvokeAsync(Api.InvokeFileIsUploadFinished, uploadToken).ConfigureAwait(false); + var anyUploadsOpen = await FilesIsUploadFinished().ConfigureAwait(false); Logger.Debug("Uploads open: " + anyUploadsOpen); while (anyUploadsOpen && !uploadToken.IsCancellationRequested) { - anyUploadsOpen = await _mareHub!.InvokeAsync(Api.InvokeFileIsUploadFinished, uploadToken).ConfigureAwait(false); + anyUploadsOpen = await FilesIsUploadFinished().ConfigureAwait(false); await Task.Delay(TimeSpan.FromSeconds(0.5), uploadToken).ConfigureAwait(false); Logger.Debug("Waiting for uploads to finish"); } @@ -267,7 +272,7 @@ public partial class ApiController sb.AppendLine($"GlamourerData for {item.Key}: {!string.IsNullOrEmpty(item.Value)}"); } Logger.Debug("Chara data contained: " + Environment.NewLine + sb.ToString()); - await _mareHub!.InvokeAsync(Api.InvokeUserPushCharacterDataToVisibleClients, character, visibleCharacterIds, uploadToken).ConfigureAwait(false); + await UserPushData(character, visibleCharacterIds).ConfigureAwait(false); } else { @@ -303,9 +308,30 @@ public partial class ApiController } } - await _mareHub!.SendAsync(Api.SendFileUploadFileStreamAsync, fileHash, AsyncFileData(uploadToken), uploadToken).ConfigureAwait(false); + await FilesUploadStreamAsync(fileHash, AsyncFileData(uploadToken)).ConfigureAwait(false); } + public async Task FilesUploadStreamAsync(string hash, IAsyncEnumerable fileContent) + { + await _mareHub!.SendAsync(nameof(FilesUploadStreamAsync), hash, fileContent).ConfigureAwait(false); + } + + public async Task FilesIsUploadFinished() + { + return await _mareHub!.InvokeAsync(nameof(FilesIsUploadFinished)).ConfigureAwait(false); + } + + public async Task> FilesGetSizes(List hashes) + { + return await _mareHub!.InvokeAsync>(nameof(FilesGetSizes), hashes).ConfigureAwait(false); + } + + public async Task> FilesSend(List fileListHashes) + { + return await _mareHub!.InvokeAsync>(nameof(FilesSend), fileListHashes).ConfigureAwait(false); + } + + public void CancelDownload(int downloadId) { while (CurrentDownloads.ContainsKey(downloadId)) diff --git a/MareSynchronos/WebAPI/ApIController.Functions.Users.cs b/MareSynchronos/WebAPI/ApIController.Functions.Users.cs index 56ec015..43135ae 100644 --- a/MareSynchronos/WebAPI/ApIController.Functions.Users.cs +++ b/MareSynchronos/WebAPI/ApIController.Functions.Users.cs @@ -7,36 +7,46 @@ namespace MareSynchronos.WebAPI; public partial class ApiController { - public async Task DeleteAccount() + public async Task UserDelete() { _pluginConfiguration.ClientSecret.Remove(ApiUri); _pluginConfiguration.Save(); - await _mareHub!.SendAsync(Api.SendFileDeleteAllFiles).ConfigureAwait(false); - await _mareHub!.SendAsync(Api.SendUserDeleteAccount).ConfigureAwait(false); + await FilesDeleteAll().ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(UserDelete)).ConfigureAwait(false); await CreateConnections().ConfigureAwait(false); } - public async Task> GetOnlineCharacters() + public async Task UserPushData(CharacterCacheDto characterCache, List visibleCharacterIds) { - return await _mareHub!.InvokeAsync>(Api.InvokeUserGetOnlineCharacters).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(UserPushData), characterCache, visibleCharacterIds).ConfigureAwait(false); } - public async Task SendPairedClientAddition(string uid) + public async Task> UserGetPairedClients() { - if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendUserPairedClientAddition, uid.Trim()).ConfigureAwait(false); + return await _mareHub!.InvokeAsync>(nameof(UserGetPairedClients)).ConfigureAwait(false); } - public async Task SendPairedClientPauseChange(string uid, bool paused) + public async Task> UserGetOnlineCharacters() { - if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendUserPairedClientPauseChange, uid, paused).ConfigureAwait(false); + return await _mareHub!.InvokeAsync>(nameof(UserGetOnlineCharacters)).ConfigureAwait(false); } - public async Task SendPairedClientRemoval(string uid) + public async Task UserAddPair(string uid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendUserPairedClientRemoval, uid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(UserAddPair), uid.Trim()).ConfigureAwait(false); + } + + public async Task UserChangePairPauseStatus(string uid, bool paused) + { + if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; + await _mareHub!.SendAsync(nameof(UserChangePairPauseStatus), uid, paused).ConfigureAwait(false); + } + + public async Task UserRemovePair(string uid) + { + if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; + await _mareHub!.SendAsync(nameof(UserRemovePair), uid).ConfigureAwait(false); } } diff --git a/MareSynchronos/WebAPI/ApiController.Functions.Admin.cs b/MareSynchronos/WebAPI/ApiController.Functions.Admin.cs index c19df84..cc61534 100644 --- a/MareSynchronos/WebAPI/ApiController.Functions.Admin.cs +++ b/MareSynchronos/WebAPI/ApiController.Functions.Admin.cs @@ -8,40 +8,50 @@ namespace MareSynchronos.WebAPI; public partial class ApiController { - public async Task AddOrUpdateForbiddenFileEntry(ForbiddenFileDto forbiddenFile) + public async Task AdminUpdateOrAddForbiddenFile(ForbiddenFileDto forbiddenFile) { - await _mareHub!.SendAsync(Api.SendAdminUpdateOrAddForbiddenFile, forbiddenFile).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(AdminUpdateOrAddForbiddenFile), forbiddenFile).ConfigureAwait(false); } - public async Task DeleteForbiddenFileEntry(ForbiddenFileDto forbiddenFile) + public async Task AdminDeleteForbiddenFile(ForbiddenFileDto forbiddenFile) { - await _mareHub!.SendAsync(Api.SendAdminDeleteForbiddenFile, forbiddenFile).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(AdminDeleteForbiddenFile), forbiddenFile).ConfigureAwait(false); } - public async Task AddOrUpdateBannedUserEntry(BannedUserDto bannedUser) + public async Task AdminUpdateOrAddBannedUser(BannedUserDto bannedUser) { - await _mareHub!.SendAsync(Api.SendAdminUpdateOrAddBannedUser, bannedUser).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(AdminUpdateOrAddBannedUser), bannedUser).ConfigureAwait(false); } - public async Task DeleteBannedUserEntry(BannedUserDto bannedUser) + public async Task AdminDeleteBannedUser(BannedUserDto bannedUser) { - await _mareHub!.SendAsync(Api.SendAdminDeleteBannedUser, bannedUser).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(AdminDeleteBannedUser), bannedUser).ConfigureAwait(false); } public async Task RefreshOnlineUsers() { - AdminOnlineUsers = await _mareHub!.InvokeAsync>(Api.InvokeAdminGetOnlineUsers).ConfigureAwait(false); + AdminOnlineUsers = await AdminGetOnlineUsers().ConfigureAwait(false); + } + + public async Task> AdminGetOnlineUsers() + { + return await _mareHub!.InvokeAsync>(nameof(AdminGetOnlineUsers)).ConfigureAwait(false); } public List AdminOnlineUsers { get; set; } = new List(); - public void PromoteToModerator(string onlineUserUID) + public async Task AdminChangeModeratorStatus(string onlineUserUID, bool isModerator) { - _mareHub!.SendAsync(Api.SendAdminChangeModeratorStatus, onlineUserUID, true); + await _mareHub!.SendAsync(nameof(AdminChangeModeratorStatus), onlineUserUID, isModerator).ConfigureAwait(false); } - public void DemoteFromModerator(string onlineUserUID) + public async Task> AdminGetForbiddenFiles() { - _mareHub!.SendAsync(Api.SendAdminChangeModeratorStatus, onlineUserUID, false); + return await _mareHub!.InvokeAsync>(nameof(AdminGetForbiddenFiles)).ConfigureAwait(false); + } + + public async Task> AdminGetBannedUsers() + { + return await _mareHub!.InvokeAsync>(nameof(AdminGetBannedUsers)).ConfigureAwait(false); } } diff --git a/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs b/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs index c4b792e..582cae4 100644 --- a/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs +++ b/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System; using System.Linq; using System.Threading.Tasks; using MareSynchronos.API; @@ -12,96 +12,115 @@ public partial class ApiController { public ClientPairDto? LastAddedUser { get; set; } - private void UserForcedReconnectCallback() + public void OnUserUpdateClientPairs(Action act) { - _ = CreateConnections(); + if (_initialized) return; + _mareHub!.On(nameof(Client_UserUpdateClientPairs), act); } - private void UpdateLocalClientPairsCallback(ClientPairDto dto) + public void OnUpdateSystemInfo(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_UpdateSystemInfo), act); + } + + public void OnUserReceiveCharacterData(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_UserReceiveCharacterData), act); + } + + public void OnUserChangePairedPlayer(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_UserChangePairedPlayer), act); + } + + public void OnGroupChange(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_GroupChange), act); + } + + public void OnGroupUserChange(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_GroupUserChange), act); + } + + public void OnAdminForcedReconnect(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_AdminForcedReconnect), act); + } + + public void OnAdminDeleteBannedUser(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_AdminDeleteBannedUser), act); + } + + public void OnAdminDeleteForbiddenFile(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_AdminDeleteForbiddenFile), act); + } + + public void OnAdminUpdateOrAddBannedUser(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_AdminUpdateOrAddBannedUser), act); + } + + public void OnAdminUpdateOrAddForbiddenFile(Action act) + { + if (_initialized) return; + _mareHub!.On(nameof(Client_AdminUpdateOrAddForbiddenFile), act); + } + + public Task Client_UserUpdateClientPairs(ClientPairDto dto) { var entry = PairedClients.SingleOrDefault(e => string.Equals(e.OtherUID, dto.OtherUID, System.StringComparison.Ordinal)); if (dto.IsRemoved) { PairedClients.RemoveAll(p => string.Equals(p.OtherUID, dto.OtherUID, System.StringComparison.Ordinal)); - return; + return Task.CompletedTask; } if (entry == null) { LastAddedUser = dto; PairedClients.Add(dto); - return; + return Task.CompletedTask; } entry.IsPaused = dto.IsPaused; entry.IsPausedFromOthers = dto.IsPausedFromOthers; entry.IsSynced = dto.IsSynced; - } - private Task ReceiveCharacterDataCallback(CharacterCacheDto character, string characterHash) - { - Logger.Verbose("Received DTO for " + characterHash); - CharacterReceived?.Invoke(null, new CharacterReceivedEventArgs(characterHash, character)); return Task.CompletedTask; } - private void UpdateOrAddBannedUserCallback(BannedUserDto obj) + public Task Client_UpdateSystemInfo(SystemInfoDto systemInfo) { - var user = AdminBannedUsers.SingleOrDefault(b => string.Equals(b.CharacterHash, obj.CharacterHash, System.StringComparison.Ordinal)); - if (user == null) - { - AdminBannedUsers.Add(obj); - } - else - { - user.Reason = obj.Reason; - } + SystemInfoDto = systemInfo; + return Task.CompletedTask; } - private void DeleteBannedUserCallback(BannedUserDto obj) + public Task Client_UserReceiveCharacterData(CharacterCacheDto clientPairDto, string characterIdent) { - AdminBannedUsers.RemoveAll(a => string.Equals(a.CharacterHash, obj.CharacterHash, System.StringComparison.Ordinal)); + Logger.Verbose("Received DTO for " + characterIdent); + CharacterReceived?.Invoke(null, new CharacterReceivedEventArgs(characterIdent, clientPairDto)); + return Task.CompletedTask; } - private void UpdateOrAddForbiddenFileCallback(ForbiddenFileDto obj) + public Task Client_UserChangePairedPlayer(string characterIdent, bool isOnline) { - var user = AdminForbiddenFiles.SingleOrDefault(b => string.Equals(b.Hash, obj.Hash, System.StringComparison.Ordinal)); - if (user == null) - { - AdminForbiddenFiles.Add(obj); - } - else - { - user.ForbiddenBy = obj.ForbiddenBy; - } + if (isOnline) PairedClientOnline?.Invoke(characterIdent); + else PairedClientOffline?.Invoke(characterIdent); + return Task.CompletedTask; } - private void DeleteForbiddenFileCallback(ForbiddenFileDto obj) - { - AdminForbiddenFiles.RemoveAll(f => string.Equals(f.Hash, obj.Hash, System.StringComparison.Ordinal)); - } - - private void GroupPairChangedCallback(GroupPairDto dto) - { - if (dto.IsRemoved.GetValueOrDefault(false)) - { - GroupPairedClients.RemoveAll(g => string.Equals(g.GroupGID, dto.GroupGID, System.StringComparison.Ordinal) && string.Equals(g.UserUID, dto.UserUID, System.StringComparison.Ordinal)); - return; - } - - var existingUser = GroupPairedClients.FirstOrDefault(f => string.Equals(f.GroupGID, dto.GroupGID, System.StringComparison.Ordinal) && string.Equals(f.UserUID, dto.UserUID, System.StringComparison.Ordinal)); - if (existingUser == null) - { - GroupPairedClients.Add(dto); - return; - } - - existingUser.IsPaused = dto.IsPaused ?? existingUser.IsPaused; - existingUser.UserAlias = dto.UserAlias ?? existingUser.UserAlias; - existingUser.IsPinned = dto.IsPinned ?? existingUser.IsPinned; - existingUser.IsModerator = dto.IsModerator ?? existingUser.IsModerator; - } - - private async Task GroupChangedCallback(GroupDto dto) + public async Task Client_GroupChange(GroupDto dto) { if (dto.IsDeleted.GetValueOrDefault(false)) { @@ -114,7 +133,7 @@ public partial class ApiController if (existingGroup == null) { Groups.Add(dto); - GroupPairedClients.AddRange(await _mareHub!.InvokeAsync>(Api.InvokeGroupGetUsersInGroup, dto.GID).ConfigureAwait(false)); + GroupPairedClients.AddRange(await GroupsGetUsersInGroup(dto.GID).ConfigureAwait(false)); return; } @@ -123,4 +142,75 @@ public partial class ApiController existingGroup.IsPaused = dto.IsPaused ?? existingGroup.IsPaused; existingGroup.IsModerator = dto.IsModerator ?? existingGroup.IsModerator; } + + public Task Client_GroupUserChange(GroupPairDto dto) + { + if (dto.IsRemoved.GetValueOrDefault(false)) + { + GroupPairedClients.RemoveAll(g => string.Equals(g.GroupGID, dto.GroupGID, System.StringComparison.Ordinal) && string.Equals(g.UserUID, dto.UserUID, System.StringComparison.Ordinal)); + return Task.CompletedTask; + } + + var existingUser = GroupPairedClients.FirstOrDefault(f => string.Equals(f.GroupGID, dto.GroupGID, System.StringComparison.Ordinal) && string.Equals(f.UserUID, dto.UserUID, System.StringComparison.Ordinal)); + if (existingUser == null) + { + GroupPairedClients.Add(dto); + return Task.CompletedTask; + } + + existingUser.IsPaused = dto.IsPaused ?? existingUser.IsPaused; + existingUser.UserAlias = dto.UserAlias ?? existingUser.UserAlias; + existingUser.IsPinned = dto.IsPinned ?? existingUser.IsPinned; + existingUser.IsModerator = dto.IsModerator ?? existingUser.IsModerator; + + return Task.CompletedTask; + } + + public Task Client_AdminForcedReconnect() + { + _ = CreateConnections(); + return Task.CompletedTask; + } + + public Task Client_AdminDeleteBannedUser(BannedUserDto dto) + { + AdminBannedUsers.RemoveAll(a => string.Equals(a.CharacterHash, dto.CharacterHash, System.StringComparison.Ordinal)); + return Task.CompletedTask; + } + + public Task Client_AdminDeleteForbiddenFile(ForbiddenFileDto dto) + { + AdminForbiddenFiles.RemoveAll(f => string.Equals(f.Hash, dto.Hash, System.StringComparison.Ordinal)); + return Task.CompletedTask; + } + + public Task Client_AdminUpdateOrAddBannedUser(BannedUserDto dto) + { + var user = AdminBannedUsers.SingleOrDefault(b => string.Equals(b.CharacterHash, dto.CharacterHash, System.StringComparison.Ordinal)); + if (user == null) + { + AdminBannedUsers.Add(dto); + } + else + { + user.Reason = dto.Reason; + } + + return Task.CompletedTask; + } + + public Task Client_AdminUpdateOrAddForbiddenFile(ForbiddenFileDto dto) + { + var user = AdminForbiddenFiles.SingleOrDefault(b => string.Equals(b.Hash, dto.Hash, System.StringComparison.Ordinal)); + if (user == null) + { + AdminForbiddenFiles.Add(dto); + } + else + { + user.ForbiddenBy = dto.ForbiddenBy; + } + + return Task.CompletedTask; + } } diff --git a/MareSynchronos/WebAPI/ApiController.Functions.Groups.cs b/MareSynchronos/WebAPI/ApiController.Functions.Groups.cs index 79e7698..716dde1 100644 --- a/MareSynchronos/WebAPI/ApiController.Functions.Groups.cs +++ b/MareSynchronos/WebAPI/ApiController.Functions.Groups.cs @@ -1,5 +1,4 @@ using MareSynchronos.API; -using MareSynchronos.Utils; using Microsoft.AspNetCore.SignalR.Client; using System.Collections.Generic; using System.Threading.Tasks; @@ -7,105 +6,105 @@ using System.Threading.Tasks; namespace MareSynchronos.WebAPI; public partial class ApiController { - public async Task CreateGroup() + public async Task GroupCreate() { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new GroupCreatedDto(); - return await _mareHub!.InvokeAsync(Api.InvokeGroupCreate).ConfigureAwait(false); + return await _mareHub!.InvokeAsync(nameof(GroupCreate)).ConfigureAwait(false); } - public async Task ChangeGroupPassword(string gid, string newpassword) + public async Task GroupChangePassword(string gid, string newpassword) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return false; - return await _mareHub!.InvokeAsync(Api.InvokeGroupChangePassword, gid, newpassword).ConfigureAwait(false); + return await _mareHub!.InvokeAsync(nameof(GroupChangePassword), gid, newpassword).ConfigureAwait(false); } - public async Task> GetGroups() + public async Task> GroupsGetAll() { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new List(); - return await _mareHub!.InvokeAsync>(Api.InvokeGroupGetGroups).ConfigureAwait(false); + return await _mareHub!.InvokeAsync>(nameof(GroupsGetAll)).ConfigureAwait(false); } - public async Task> GetUsersInGroup(string gid) + public async Task> GroupsGetUsersInGroup(string gid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new List(); - return await _mareHub!.InvokeAsync>(Api.InvokeGroupGetUsersInGroup, gid).ConfigureAwait(false); + return await _mareHub!.InvokeAsync>(nameof(GroupsGetUsersInGroup), gid).ConfigureAwait(false); } - public async Task SendGroupJoin(string gid, string password) + public async Task GroupJoin(string gid, string password) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return false; - return await _mareHub!.InvokeAsync(Api.InvokeGroupJoin, gid.Trim(), password).ConfigureAwait(false); + return await _mareHub!.InvokeAsync(nameof(GroupJoin), gid.Trim(), password).ConfigureAwait(false); } - public async Task SendGroupChangeInviteState(string gid, bool opened) + public async Task GroupChangeInviteState(string gid, bool opened) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupChangeInviteState, gid, opened).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupChangeInviteState), gid, opened).ConfigureAwait(false); } - public async Task SendDeleteGroup(string gid) + public async Task GroupDelete(string gid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupDelete, gid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupDelete), gid).ConfigureAwait(false); } - public async Task SendChangeUserPinned(string gid, string uid, bool isPinned) + public async Task GroupChangePinned(string gid, string uid, bool isPinned) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupChangePinned, gid, uid, isPinned).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupChangePinned), gid, uid, isPinned).ConfigureAwait(false); } - public async Task SendClearGroup(string gid) + public async Task GroupClear(string gid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupClear, gid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupClear), gid).ConfigureAwait(false); } - public async Task SendLeaveGroup(string gid) + public async Task GroupLeave(string gid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupLeave, gid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupLeave), gid).ConfigureAwait(false); } - public async Task SendPauseGroup(string gid, bool isPaused) + public async Task GroupChangePauseState(string gid, bool isPaused) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupPause, gid, isPaused).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupChangePauseState), gid, isPaused).ConfigureAwait(false); } - public async Task SendRemoveUserFromGroup(string gid, string uid) + public async Task GroupRemoveUser(string gid, string uid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupRemoveUser, gid, uid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupRemoveUser), gid, uid).ConfigureAwait(false); } - public async Task ChangeOwnerOfGroup(string gid, string uid) + public async Task GroupChangeOwnership(string gid, string uid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupChangeOwner, gid, uid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupChangeOwnership), gid, uid).ConfigureAwait(false); } - public async Task BanUserFromGroup(string gid, string uid, string reason) + public async Task GroupBanUser(string gid, string uid, string reason) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendBanUserFromGroup, gid, uid, reason).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupBanUser), gid, uid, reason).ConfigureAwait(false); } - public async Task UnbanUserFromGroup(string gid, string uid) + public async Task GroupUnbanUser(string gid, string uid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendUnbanUserFromGroup, gid, uid).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupUnbanUser), gid, uid).ConfigureAwait(false); } - public async Task> GetBannedUsersForGroup(string gid) + public async Task> GroupGetBannedUsers(string gid) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return new(); - return await _mareHub!.InvokeAsync>(Api.InvokeGetBannedUsersForGroup, gid).ConfigureAwait(false); + return await _mareHub!.InvokeAsync>(nameof(GroupGetBannedUsers), gid).ConfigureAwait(false); } - public async Task SetModeratorForGroup(string gid, string uid, bool isModerator) + public async Task GroupSetModerator(string gid, string uid, bool isModerator) { if (!IsConnected || string.Equals(SecretKey, "-", System.StringComparison.Ordinal)) return; - await _mareHub!.SendAsync(Api.SendGroupSetModerator, gid, uid, isModerator).ConfigureAwait(false); + await _mareHub!.SendAsync(nameof(GroupSetModerator), gid, uid, isModerator).ConfigureAwait(false); } } \ No newline at end of file diff --git a/MareSynchronos/WebAPI/ApiController.cs b/MareSynchronos/WebAPI/ApiController.cs index a84923f..4c49b35 100644 --- a/MareSynchronos/WebAPI/ApiController.cs +++ b/MareSynchronos/WebAPI/ApiController.cs @@ -18,12 +18,12 @@ namespace MareSynchronos.WebAPI; public delegate void SimpleStringDelegate(string str); -public partial class ApiController : IDisposable +public partial class ApiController : IDisposable, IMareHubClient { public const string MainServer = "Lunae Crescere Incipientis (Central Server EU)"; public const string MainServiceUri = "wss://maresynchronos.com"; - public readonly int[] SupportedServerVersions = { Api.Version }; + public readonly int[] SupportedServerVersions = { IMareHub.ApiVersion }; private readonly Configuration _pluginConfiguration; private readonly DalamudUtil _dalamudUtil; @@ -122,6 +122,8 @@ public partial class ApiController : IDisposable public int OnlineUsers => SystemInfoDto.OnlineUsers; private ServerState _serverState; + private bool _initialized; + public ServerState ServerState { get => _serverState; @@ -175,18 +177,17 @@ public partial class ApiController : IDisposable if (token.IsCancellationRequested) break; - _mareHub = BuildHubConnection(Api.Path); + _mareHub = BuildHubConnection(IMareHub.Path); await _mareHub.StartAsync(token).ConfigureAwait(false); - _mareHub.On(Api.OnUpdateSystemInfo, (dto) => SystemInfoDto = dto); + OnUpdateSystemInfo((dto) => Client_UpdateSystemInfo(dto)); - _connectionDto = - await _mareHub.InvokeAsync(Api.InvokeHeartbeat, _dalamudUtil.PlayerNameHashed, token).ConfigureAwait(false); + _connectionDto = await Heartbeat(_dalamudUtil.PlayerNameHashed).ConfigureAwait(false); ServerState = ServerState.Connected; - if (_connectionDto.ServerVersion != Api.Version) + if (_connectionDto.ServerVersion != IMareHub.ApiVersion) { ServerState = ServerState.VersionMisMatch; await StopConnection(token).ConfigureAwait(false); @@ -254,7 +255,7 @@ public partial class ApiController : IDisposable { await Task.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); if (ct.IsCancellationRequested) break; - var needsRestart = await _mareHub!.InvokeAsync(Api.InvokeCheckClientHealth, ct).ConfigureAwait(false); + var needsRestart = await CheckClientHealth().ConfigureAwait(false); Logger.Debug("Checked Client Health State, healthy: " + !needsRestart); if (needsRestart) { @@ -268,42 +269,30 @@ public partial class ApiController : IDisposable if (_mareHub == null) return; Logger.Debug("Initializing data"); - _mareHub.On(Api.OnUserUpdateClientPairs, - UpdateLocalClientPairsCallback); - _mareHub.On(Api.OnUserReceiveCharacterData, - ReceiveCharacterDataCallback); - _mareHub.On(Api.OnUserRemoveOnlinePairedPlayer, - (s) => PairedClientOffline?.Invoke(s)); - _mareHub.On(Api.OnUserAddOnlinePairedPlayer, - (s) => PairedClientOnline?.Invoke(s)); - _mareHub.On(Api.OnAdminForcedReconnect, UserForcedReconnectCallback); - _mareHub.On(Api.OnGroupChange, GroupChangedCallback); - _mareHub.On(Api.OnGroupUserChange, GroupPairChangedCallback); + OnUserUpdateClientPairs((dto) => Client_UserUpdateClientPairs(dto)); + OnUserChangePairedPlayer((ident, online) => Client_UserChangePairedPlayer(ident, online)); + OnUserReceiveCharacterData((dto, ident) => Client_UserReceiveCharacterData(dto, ident)); + OnGroupChange(async (dto) => await Client_GroupChange(dto).ConfigureAwait(false)); + OnGroupUserChange((dto) => Client_GroupUserChange(dto)); - PairedClients = - await _mareHub!.InvokeAsync>(Api.InvokeUserGetPairedClients, token).ConfigureAwait(false); - Groups = await GetGroups().ConfigureAwait(false); + OnAdminForcedReconnect(() => Client_AdminForcedReconnect()); + + PairedClients = await UserGetPairedClients().ConfigureAwait(false); + Groups = await GroupsGetAll().ConfigureAwait(false); GroupPairedClients.Clear(); foreach (var group in Groups) { - GroupPairedClients.AddRange(await GetUsersInGroup(group.GID).ConfigureAwait(false)); + GroupPairedClients.AddRange(await GroupsGetUsersInGroup(group.GID).ConfigureAwait(false)); } if (IsModerator) { - AdminForbiddenFiles = - await _mareHub.InvokeAsync>(Api.InvokeAdminGetForbiddenFiles, - token).ConfigureAwait(false); - AdminBannedUsers = - await _mareHub.InvokeAsync>(Api.InvokeAdminGetBannedUsers, - token).ConfigureAwait(false); - _mareHub.On(Api.OnAdminUpdateOrAddBannedUser, - UpdateOrAddBannedUserCallback); - _mareHub.On(Api.OnAdminDeleteBannedUser, DeleteBannedUserCallback); - _mareHub.On(Api.OnAdminUpdateOrAddForbiddenFile, - UpdateOrAddForbiddenFileCallback); - _mareHub.On(Api.OnAdminDeleteForbiddenFile, - DeleteForbiddenFileCallback); + AdminForbiddenFiles = await AdminGetForbiddenFiles().ConfigureAwait(false); + AdminBannedUsers = await AdminGetBannedUsers().ConfigureAwait(false); + OnAdminUpdateOrAddBannedUser((dto) => Client_AdminUpdateOrAddBannedUser(dto)); + OnAdminDeleteBannedUser((dto) => Client_AdminDeleteBannedUser(dto)); + OnAdminUpdateOrAddForbiddenFile(dto => Client_AdminUpdateOrAddForbiddenFile(dto)); + OnAdminDeleteForbiddenFile(dto => Client_AdminDeleteForbiddenFile(dto)); } _healthCheckTokenSource?.Cancel(); @@ -311,6 +300,7 @@ public partial class ApiController : IDisposable _healthCheckTokenSource = new CancellationTokenSource(); _ = ClientHealthCheck(_healthCheckTokenSource.Token); + _initialized = true; Connected?.Invoke(); } @@ -370,6 +360,7 @@ public partial class ApiController : IDisposable { if (_mareHub is not null) { + _initialized = false; _uploadCancellationTokenSource?.Cancel(); Logger.Info("Stopping existing connection"); _mareHub.Closed -= MareHubOnClosed; @@ -392,4 +383,14 @@ public partial class ApiController : IDisposable } } } + + public async Task Heartbeat(string characterIdentification) + { + return await _mareHub!.InvokeAsync(nameof(Heartbeat), characterIdentification).ConfigureAwait(false); + } + + public async Task CheckClientHealth() + { + return await _mareHub!.InvokeAsync(nameof(CheckClientHealth)).ConfigureAwait(false); + } }