fix crash on logout, change several logger.debug to verbose, adjustments to player cache generation, fixes to file scan manager, better handling disconnects, some refactoring, adjustments to intro UI, correct display of server state

This commit is contained in:
Stanley Dimant
2022-07-04 01:52:08 +02:00
parent 7a58321ea0
commit db4d5f37f9
21 changed files with 283 additions and 273 deletions

View File

@@ -75,7 +75,7 @@ namespace MareSynchronos
public Dictionary<string, Dictionary<string, string>> UidServerComments { get; set; } = new(); public Dictionary<string, Dictionary<string, string>> UidServerComments { get; set; } = new();
public Dictionary<string, string> UidComments { get; set; } = new(); public Dictionary<string, string> UidComments { get; set; } = new();
public int Version { get; set; } = 1; public int Version { get; set; } = 3;
public bool ShowTransferWindow { get; set; } = true; public bool ShowTransferWindow { get; set; } = true;
@@ -143,6 +143,17 @@ namespace MareSynchronos
Version = 2; Version = 2;
Save(); Save();
} }
if (Version == 2)
{
Logger.Debug("Migrating Configuration from V2 to V3");
ApiUri = "wss://v2202207178628194299.powersrv.de:6871";
ClientSecret.Clear();
UidServerComments.Clear();
Version = 3;
Save();
}
} }
} }
} }

View File

@@ -22,7 +22,7 @@ public class CharacterDataFactory
public CharacterDataFactory(DalamudUtil dalamudUtil, IpcManager ipcManager) public CharacterDataFactory(DalamudUtil dalamudUtil, IpcManager ipcManager)
{ {
Logger.Debug("Creating " + nameof(CharacterDataFactory)); Logger.Verbose("Creating " + nameof(CharacterDataFactory));
_dalamudUtil = dalamudUtil; _dalamudUtil = dalamudUtil;
_ipcManager = ipcManager; _ipcManager = ipcManager;
@@ -48,8 +48,8 @@ public class CharacterDataFactory
var indentation = GetIndentationForInheritanceLevel(inheritanceLevel); var indentation = GetIndentationForInheritanceLevel(inheritanceLevel);
objectKind += string.IsNullOrEmpty(objectKind) ? "" : " "; objectKind += string.IsNullOrEmpty(objectKind) ? "" : " ";
Logger.Debug(indentation.Item1 + objectKind + resourceType + " [" + string.Join(", ", fileReplacement.GamePaths) + "]"); Logger.Verbose(indentation.Item1 + objectKind + resourceType + " [" + string.Join(", ", fileReplacement.GamePaths) + "]");
Logger.Debug(indentation.Item2 + "=> " + fileReplacement.ResolvedPath); Logger.Verbose(indentation.Item2 + "=> " + fileReplacement.ResolvedPath);
} }
private unsafe void AddReplacementsFromRenderModel(RenderModel* mdl, CharacterData cache, int inheritanceLevel = 0, string objectKind = "") private unsafe void AddReplacementsFromRenderModel(RenderModel* mdl, CharacterData cache, int inheritanceLevel = 0, string objectKind = "")
@@ -116,7 +116,7 @@ public class CharacterDataFactory
Stopwatch st = Stopwatch.StartNew(); Stopwatch st = Stopwatch.StartNew();
while (!_dalamudUtil.IsPlayerPresent) while (!_dalamudUtil.IsPlayerPresent)
{ {
Logger.Debug("Character is null but it shouldn't be, waiting"); Logger.Verbose("Character is null but it shouldn't be, waiting");
Thread.Sleep(50); Thread.Sleep(50);
} }
_dalamudUtil.WaitWhileCharacterIsDrawing(_dalamudUtil.PlayerPointer); _dalamudUtil.WaitWhileCharacterIsDrawing(_dalamudUtil.PlayerPointer);

View File

@@ -10,8 +10,26 @@ namespace MareSynchronos.FileCacheDB
{ {
public partial class FileCacheContext : DbContext public partial class FileCacheContext : DbContext
{ {
public FileCacheContext() private string DbPath { get; set; }
public FileCacheContext()
{ {
DbPath = Path.Combine(Plugin.PluginInterface.ConfigDirectory.FullName, "FileCache.db");
string oldDbPath = Path.Combine(Plugin.PluginInterface.ConfigDirectory.FullName, "FileCacheDebug.db");
if (!Directory.Exists(Plugin.PluginInterface.ConfigDirectory.FullName))
{
Directory.CreateDirectory(Plugin.PluginInterface.ConfigDirectory.FullName);
}
var veryOldDbPath = Path.Combine(Plugin.PluginInterface.ConfigDirectory.FullName, "..", "FileCacheDebug.db");
if (File.Exists(veryOldDbPath))
{
Logger.Debug("Migrated old path to new path");
File.Move(veryOldDbPath, oldDbPath, true);
}
if (File.Exists(oldDbPath))
{
File.Move(oldDbPath, DbPath, true);
}
Database.EnsureCreated(); Database.EnsureCreated();
} }
@@ -26,19 +44,7 @@ namespace MareSynchronos.FileCacheDB
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
string dbPath = Path.Combine(Plugin.PluginInterface.ConfigDirectory.FullName, "FileCacheDebug.db"); optionsBuilder.UseSqlite("Data Source=" + DbPath);
if(!Directory.Exists(Plugin.PluginInterface.ConfigDirectory.FullName))
{
Directory.CreateDirectory(Plugin.PluginInterface.ConfigDirectory.FullName);
}
var oldDbPath = Path.Combine(Plugin.PluginInterface.ConfigDirectory.FullName, "..", "FileCacheDebug.db");
if (File.Exists(oldDbPath))
{
Logger.Debug("Migrated old path to new path");
File.Move(oldDbPath, dbPath, true);
}
//PluginLog.Debug("Using Database " + dbPath);
optionsBuilder.UseSqlite("Data Source=" + dbPath);
} }
} }

View File

@@ -178,12 +178,13 @@ public class CachedPlayer
public void DisposePlayer() public void DisposePlayer()
{ {
Logger.Debug("Disposing " + PlayerName + " (" + PlayerNameHash + ")");
if (_isDisposed) return; if (_isDisposed) return;
if (string.IsNullOrEmpty(PlayerName)) return; if (string.IsNullOrEmpty(PlayerName)) return;
Logger.Verbose("Disposing " + PlayerName + " (" + PlayerNameHash + ")");
_isDisposed = true;
try try
{ {
Logger.Debug("Restoring state for " + PlayerName); Logger.Verbose("Restoring state for " + PlayerName);
_dalamudUtil.FrameworkUpdate -= DalamudUtilOnFrameworkUpdate; _dalamudUtil.FrameworkUpdate -= DalamudUtilOnFrameworkUpdate;
_ipcManager.PenumbraRedrawEvent -= IpcManagerOnPenumbraRedrawEvent; _ipcManager.PenumbraRedrawEvent -= IpcManagerOnPenumbraRedrawEvent;
_apiController.CharacterReceived -= ApiControllerOnCharacterReceived; _apiController.CharacterReceived -= ApiControllerOnCharacterReceived;
@@ -191,7 +192,7 @@ public class CachedPlayer
_downloadCancellationTokenSource?.Dispose(); _downloadCancellationTokenSource?.Dispose();
_downloadCancellationTokenSource = null; _downloadCancellationTokenSource = null;
_ipcManager.PenumbraRemoveTemporaryCollection(PlayerName); _ipcManager.PenumbraRemoveTemporaryCollection(PlayerName);
if (PlayerCharacter != null) if (PlayerCharacter != null && PlayerCharacter.IsValid())
{ {
_ipcManager.GlamourerApplyOnlyCustomization(_originalGlamourerData, PlayerCharacter); _ipcManager.GlamourerApplyOnlyCustomization(_originalGlamourerData, PlayerCharacter);
_ipcManager.GlamourerApplyOnlyEquipment(_lastGlamourerData, PlayerCharacter); _ipcManager.GlamourerApplyOnlyEquipment(_lastGlamourerData, PlayerCharacter);
@@ -206,7 +207,6 @@ public class CachedPlayer
PlayerName = string.Empty; PlayerName = string.Empty;
PlayerCharacter = null; PlayerCharacter = null;
IsVisible = false; IsVisible = false;
_isDisposed = true;
} }
} }

View File

@@ -25,22 +25,22 @@ namespace MareSynchronos.Managers
private Task? _scanTask; private Task? _scanTask;
public FileCacheManager(IpcManager ipcManager, Configuration pluginConfiguration) public FileCacheManager(IpcManager ipcManager, Configuration pluginConfiguration)
{ {
Logger.Debug("Creating " + nameof(FileCacheManager)); Logger.Verbose("Creating " + nameof(FileCacheManager));
_ipcManager = ipcManager; _ipcManager = ipcManager;
_pluginConfiguration = pluginConfiguration; _pluginConfiguration = pluginConfiguration;
StartWatchersAndScan(); StartWatchersAndScan();
_ipcManager.PenumbraInitialized += IpcManagerOnPenumbraInitialized; _ipcManager.PenumbraInitialized += StartWatchersAndScan;
_ipcManager.PenumbraDisposed += IpcManagerOnPenumbraDisposed; _ipcManager.PenumbraDisposed += StopWatchersAndScan;
} }
public long CurrentFileProgress { get; private set; } public long CurrentFileProgress { get; private set; }
public long FileCacheSize { get; set; } public long FileCacheSize { get; set; }
public bool IsScanRunning => !_scanTask?.IsCompleted ?? false; public bool IsScanRunning => CurrentFileProgress > 0 || TotalFiles > 0;
public long TotalFiles { get; private set; } public long TotalFiles { get; private set; }
@@ -67,10 +67,10 @@ namespace MareSynchronos.Managers
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(FileCacheManager)); Logger.Verbose("Disposing " + nameof(FileCacheManager));
_ipcManager.PenumbraInitialized -= IpcManagerOnPenumbraInitialized; _ipcManager.PenumbraInitialized -= StartWatchersAndScan;
_ipcManager.PenumbraDisposed -= IpcManagerOnPenumbraDisposed; _ipcManager.PenumbraDisposed -= StopWatchersAndScan;
_rescanTaskCancellationTokenSource?.Cancel(); _rescanTaskCancellationTokenSource?.Cancel();
_rescanTaskRunCancellationTokenSource?.Cancel(); _rescanTaskRunCancellationTokenSource?.Cancel();
_scanCancellationTokenSource?.Cancel(); _scanCancellationTokenSource?.Cancel();
@@ -121,16 +121,6 @@ namespace MareSynchronos.Managers
Task.Run(RecalculateFileCacheSize); Task.Run(RecalculateFileCacheSize);
} }
private void IpcManagerOnPenumbraDisposed(object? sender, EventArgs e)
{
StopWatchersAndScan();
}
private void IpcManagerOnPenumbraInitialized(object? sender, EventArgs e)
{
StartWatchersAndScan();
}
private bool IsFileLocked(FileInfo file) private bool IsFileLocked(FileInfo file)
{ {
try try
@@ -217,6 +207,7 @@ namespace MareSynchronos.Managers
private async Task StartFileScan(CancellationToken ct) private async Task StartFileScan(CancellationToken ct)
{ {
TotalFiles = 1;
_scanCancellationTokenSource = new CancellationTokenSource(); _scanCancellationTokenSource = new CancellationTokenSource();
var penumbraDir = _ipcManager.PenumbraModDirectory()!; var penumbraDir = _ipcManager.PenumbraModDirectory()!;
Logger.Debug("Getting files from " + penumbraDir + " and " + _pluginConfiguration.CacheFolder); Logger.Debug("Getting files from " + penumbraDir + " and " + _pluginConfiguration.CacheFolder);
@@ -237,7 +228,7 @@ namespace MareSynchronos.Managers
var fileCachesToDelete = new ConcurrentBag<FileCache>(); var fileCachesToDelete = new ConcurrentBag<FileCache>();
var fileCachesToAdd = new ConcurrentBag<FileCache>(); var fileCachesToAdd = new ConcurrentBag<FileCache>();
Logger.Debug("Getting file list from Database"); Logger.Verbose("Getting file list from Database");
// scan files from database // scan files from database
Parallel.ForEach(fileCaches, new ParallelOptions() Parallel.ForEach(fileCaches, new ParallelOptions()
{ {

View File

@@ -7,6 +7,7 @@ using System.Linq;
using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Game.ClientState.Objects.Types;
using Lumina.Excel.GeneratedSheets; using Lumina.Excel.GeneratedSheets;
using MareSynchronos.Utils; using MareSynchronos.Utils;
using MareSynchronos.WebAPI;
namespace MareSynchronos.Managers namespace MareSynchronos.Managers
{ {
@@ -33,7 +34,7 @@ namespace MareSynchronos.Managers
_penumbraSetTemporaryMod; _penumbraSetTemporaryMod;
public IpcManager(DalamudPluginInterface pi) public IpcManager(DalamudPluginInterface pi)
{ {
Logger.Debug("Creating " + nameof(IpcManager)); Logger.Verbose("Creating " + nameof(IpcManager));
_penumbraInit = pi.GetIpcSubscriber<object>("Penumbra.Initialized"); _penumbraInit = pi.GetIpcSubscriber<object>("Penumbra.Initialized");
_penumbraDispose = pi.GetIpcSubscriber<object>("Penumbra.Disposed"); _penumbraDispose = pi.GetIpcSubscriber<object>("Penumbra.Disposed");
@@ -69,12 +70,12 @@ namespace MareSynchronos.Managers
if (Initialized) if (Initialized)
{ {
PenumbraInitialized?.Invoke(null, EventArgs.Empty); PenumbraInitialized?.Invoke();
} }
} }
public event EventHandler? PenumbraInitialized; public event VoidDelegate? PenumbraInitialized;
public event EventHandler? PenumbraDisposed; public event VoidDelegate? PenumbraDisposed;
public event EventHandler? PenumbraRedrawEvent; public event EventHandler? PenumbraRedrawEvent;
public bool Initialized => CheckPenumbraApi(); public bool Initialized => CheckPenumbraApi();
@@ -104,32 +105,31 @@ namespace MareSynchronos.Managers
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(IpcManager)); Logger.Verbose("Disposing " + nameof(IpcManager));
_penumbraDispose.Unsubscribe(PenumbraDispose); _penumbraDispose.Unsubscribe(PenumbraDispose);
_penumbraInit.Unsubscribe(PenumbraInit); _penumbraInit.Unsubscribe(PenumbraInit);
_penumbraObjectIsRedrawn.Unsubscribe(RedrawEvent); _penumbraObjectIsRedrawn.Unsubscribe(RedrawEvent);
Logger.Debug("IPC Manager disposed");
} }
public void GlamourerApplyAll(string customization, GameObject character) public void GlamourerApplyAll(string customization, GameObject character)
{ {
if (!CheckGlamourerApi()) return; if (!CheckGlamourerApi()) return;
Logger.Debug("Glamourer apply all to " + character); Logger.Verbose("Glamourer apply all to " + character);
_glamourerApplyAll!.InvokeAction(customization, character); _glamourerApplyAll!.InvokeAction(customization, character);
} }
public void GlamourerApplyOnlyEquipment(string customization, GameObject character) public void GlamourerApplyOnlyEquipment(string customization, GameObject character)
{ {
if (!CheckGlamourerApi() || string.IsNullOrEmpty(customization)) return; if (!CheckGlamourerApi() || string.IsNullOrEmpty(customization)) return;
Logger.Debug("Glamourer apply only equipment to " + character); Logger.Verbose("Glamourer apply only equipment to " + character);
_glamourerApplyOnlyEquipment!.InvokeAction(customization, character); _glamourerApplyOnlyEquipment!.InvokeAction(customization, character);
} }
public void GlamourerApplyOnlyCustomization(string customization, GameObject character) public void GlamourerApplyOnlyCustomization(string customization, GameObject character)
{ {
if (!CheckGlamourerApi() || string.IsNullOrEmpty(customization)) return; if (!CheckGlamourerApi() || string.IsNullOrEmpty(customization)) return;
Logger.Debug("Glamourer apply only customization to " + character); Logger.Verbose("Glamourer apply only customization to " + character);
_glamourerApplyOnlyCustomization!.InvokeAction(customization, character); _glamourerApplyOnlyCustomization!.InvokeAction(customization, character);
} }
@@ -148,7 +148,7 @@ namespace MareSynchronos.Managers
public string PenumbraCreateTemporaryCollection(string characterName) public string PenumbraCreateTemporaryCollection(string characterName)
{ {
if (!CheckPenumbraApi()) return string.Empty; if (!CheckPenumbraApi()) return string.Empty;
Logger.Debug("Creating temp collection for " + characterName); Logger.Verbose("Creating temp collection for " + characterName);
var ret = _penumbraCreateTemporaryCollection.InvokeFunc("MareSynchronos", characterName, true); var ret = _penumbraCreateTemporaryCollection.InvokeFunc("MareSynchronos", characterName, true);
return ret.Item2; return ret.Item2;
} }
@@ -174,7 +174,7 @@ namespace MareSynchronos.Managers
public void PenumbraRemoveTemporaryCollection(string characterName) public void PenumbraRemoveTemporaryCollection(string characterName)
{ {
if (!CheckPenumbraApi()) return; if (!CheckPenumbraApi()) return;
Logger.Debug("Removing temp collection for " + characterName); Logger.Verbose("Removing temp collection for " + characterName);
_penumbraRemoveTemporaryCollection.InvokeFunc(characterName); _penumbraRemoveTemporaryCollection.InvokeFunc(characterName);
} }
@@ -182,7 +182,7 @@ namespace MareSynchronos.Managers
{ {
if (!CheckPenumbraApi()) return null; if (!CheckPenumbraApi()) return null;
var resolvedPath = _penumbraResolvePath!.InvokeFunc(path, characterName); var resolvedPath = _penumbraResolvePath!.InvokeFunc(path, characterName);
PluginLog.Verbose("Resolving " + path + Environment.NewLine + "=>" + string.Join(", ", resolvedPath)); Logger.Verbose("Resolved " + path + "=>" + string.Join(", ", resolvedPath));
return resolvedPath; return resolvedPath;
} }
@@ -190,7 +190,7 @@ namespace MareSynchronos.Managers
{ {
if (!CheckPenumbraApi()) return new[] { path }; if (!CheckPenumbraApi()) return new[] { path };
var resolvedPaths = _penumbraReverseResolvePath!.InvokeFunc(path, characterName); var resolvedPaths = _penumbraReverseResolvePath!.InvokeFunc(path, characterName);
PluginLog.Verbose("ReverseResolving " + path + Environment.NewLine + "=>" + string.Join(", ", resolvedPaths)); Logger.Verbose("Reverse Resolved " + path + "=>" + string.Join(", ", resolvedPaths));
return resolvedPaths; return resolvedPaths;
} }
@@ -198,7 +198,7 @@ namespace MareSynchronos.Managers
{ {
if (!CheckPenumbraApi()) return; if (!CheckPenumbraApi()) return;
Logger.Debug("Assigning temp mods for " + collectionName); Logger.Verbose("Assigning temp mods for " + collectionName);
foreach (var mod in modPaths) foreach (var mod in modPaths)
{ {
Logger.Verbose(mod.Key + " => " + mod.Value); Logger.Verbose(mod.Key + " => " + mod.Value);
@@ -213,13 +213,13 @@ namespace MareSynchronos.Managers
private void PenumbraInit() private void PenumbraInit()
{ {
PenumbraInitialized?.Invoke(null, EventArgs.Empty); PenumbraInitialized?.Invoke();
_penumbraRedraw!.InvokeAction("self", 0); _penumbraRedraw!.InvokeAction("self", 0);
} }
private void PenumbraDispose() private void PenumbraDispose()
{ {
PenumbraDisposed?.Invoke(null, EventArgs.Empty); PenumbraDisposed?.Invoke();
} }
} }
} }

View File

@@ -27,7 +27,7 @@ public class OnlinePlayerManager : IDisposable
public OnlinePlayerManager(Framework framework, ApiController apiController, DalamudUtil dalamudUtil, IpcManager ipcManager, PlayerManager playerManager) public OnlinePlayerManager(Framework framework, ApiController apiController, DalamudUtil dalamudUtil, IpcManager ipcManager, PlayerManager playerManager)
{ {
Logger.Debug("Creating " + nameof(OnlinePlayerManager)); Logger.Verbose("Creating " + nameof(OnlinePlayerManager));
_framework = framework; _framework = framework;
_apiController = apiController; _apiController = apiController;
@@ -74,7 +74,7 @@ public class OnlinePlayerManager : IDisposable
PushCharacterData(OnlineVisiblePlayerHashes); PushCharacterData(OnlineVisiblePlayerHashes);
} }
private void ApiControllerOnConnected(object? sender, EventArgs e) private void ApiControllerOnConnected()
{ {
var apiTask = _apiController.GetOnlineCharacters(); var apiTask = _apiController.GetOnlineCharacters();
@@ -95,12 +95,12 @@ public class OnlinePlayerManager : IDisposable
_framework.Update += FrameworkOnUpdate; _framework.Update += FrameworkOnUpdate;
} }
private void IpcManagerOnPenumbraDisposed(object? sender, EventArgs e) private void IpcManagerOnPenumbraDisposed()
{ {
_onlineCachedPlayers.ForEach(p => p.DisposePlayer()); _onlineCachedPlayers.ForEach(p => p.DisposePlayer());
} }
private void ApiControllerOnDisconnected(object? sender, EventArgs e) private void ApiControllerOnDisconnected()
{ {
RestoreAllCharacters(); RestoreAllCharacters();
_playerManager.PlayerHasChanged -= PlayerManagerOnPlayerHasChanged; _playerManager.PlayerHasChanged -= PlayerManagerOnPlayerHasChanged;
@@ -110,12 +110,12 @@ public class OnlinePlayerManager : IDisposable
{ {
_onlineCachedPlayers.Clear(); _onlineCachedPlayers.Clear();
_onlineCachedPlayers.AddRange(apiTaskResult.Select(CreateCachedPlayer)); _onlineCachedPlayers.AddRange(apiTaskResult.Select(CreateCachedPlayer));
Logger.Debug("Online and paired users: " + string.Join(",", _onlineCachedPlayers)); Logger.Verbose("Online and paired users: " + string.Join(Environment.NewLine, _onlineCachedPlayers));
} }
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(OnlinePlayerManager)); Logger.Verbose("Disposing " + nameof(OnlinePlayerManager));
RestoreAllCharacters(); RestoreAllCharacters();
@@ -140,37 +140,28 @@ public class OnlinePlayerManager : IDisposable
_onlineCachedPlayers.Clear(); _onlineCachedPlayers.Clear();
} }
public async Task UpdatePlayersFromService(Dictionary<string, int> playerJobIds) private void ApiControllerOnPairedClientOffline(string charHash)
{ {
if (!playerJobIds.Any()) return; Logger.Debug("Player offline: " + charHash);
Logger.Debug("Getting data for new players: " + string.Join(Environment.NewLine, playerJobIds)); RemovePlayer(charHash);
await _apiController.GetCharacterData(playerJobIds);
} }
private void ApiControllerOnPairedClientOffline(object? sender, EventArgs e) private void ApiControllerOnPairedClientOnline(string charHash)
{ {
Logger.Debug("Player offline: " + sender!); Logger.Debug("Player online: " + charHash);
RemovePlayer((string)sender!); AddPlayer(charHash);
}
private void ApiControllerOnPairedClientOnline(object? sender, EventArgs e)
{
Logger.Debug("Player online: " + sender!);
AddPlayer((string)sender!);
return; return;
} }
private void ApiControllerOnPairedWithOther(object? sender, EventArgs e) private void ApiControllerOnPairedWithOther(string charHash)
{ {
var characterHash = (string?)sender; if (string.IsNullOrEmpty(charHash)) return;
if (string.IsNullOrEmpty(characterHash)) return; Logger.Debug("Pairing with " + charHash);
Logger.Debug("Pairing with " + characterHash); AddPlayer(charHash);
AddPlayer(characterHash);
} }
private void ApiControllerOnUnpairedFromOther(object? sender, EventArgs e) private void ApiControllerOnUnpairedFromOther(string? characterHash)
{ {
var characterHash = (string?)sender;
if (string.IsNullOrEmpty(characterHash)) return; if (string.IsNullOrEmpty(characterHash)) return;
Logger.Debug("Unpairing from " + characterHash); Logger.Debug("Unpairing from " + characterHash);
RemovePlayer(characterHash); RemovePlayer(characterHash);
@@ -228,8 +219,8 @@ public class OnlinePlayerManager : IDisposable
{ {
Task.Run(async () => Task.Run(async () =>
{ {
Logger.Verbose(JsonConvert.SerializeObject(_playerManager.LastSentCharacterData!.ToCharacterCacheDto(), Formatting.Indented)); Logger.Verbose(JsonConvert.SerializeObject(_playerManager.LastSentCharacterData, Formatting.Indented));
await _apiController.PushCharacterData(_playerManager.LastSentCharacterData.ToCharacterCacheDto(), await _apiController.PushCharacterData(_playerManager.LastSentCharacterData,
visiblePlayers); visiblePlayers);
}); });
} }

View File

@@ -22,7 +22,7 @@ namespace MareSynchronos.Managers
private readonly IpcManager _ipcManager; private readonly IpcManager _ipcManager;
public event PlayerHasChanged? PlayerHasChanged; public event PlayerHasChanged? PlayerHasChanged;
public bool SendingData { get; private set; } public bool SendingData { get; private set; }
public CharacterData? LastSentCharacterData { get; private set; } public CharacterCacheDto? LastSentCharacterData { get; private set; }
private CancellationTokenSource? _playerChangedCts; private CancellationTokenSource? _playerChangedCts;
private DateTime _lastPlayerObjectCheck; private DateTime _lastPlayerObjectCheck;
@@ -31,28 +31,28 @@ namespace MareSynchronos.Managers
public PlayerManager(ApiController apiController, IpcManager ipcManager, public PlayerManager(ApiController apiController, IpcManager ipcManager,
CharacterDataFactory characterDataFactory, DalamudUtil dalamudUtil) CharacterDataFactory characterDataFactory, DalamudUtil dalamudUtil)
{ {
Logger.Debug("Creating " + nameof(PlayerManager)); Logger.Verbose("Creating " + nameof(PlayerManager));
_apiController = apiController; _apiController = apiController;
_ipcManager = ipcManager; _ipcManager = ipcManager;
_characterDataFactory = characterDataFactory; _characterDataFactory = characterDataFactory;
_dalamudUtil = dalamudUtil; _dalamudUtil = dalamudUtil;
_apiController.Connected += ApiController_Connected; _apiController.Connected += ApiControllerOnConnected;
_apiController.Disconnected += ApiController_Disconnected; _apiController.Disconnected += ApiController_Disconnected;
Logger.Debug("Watching Player, ApiController is Connected: " + _apiController.IsConnected); Logger.Debug("Watching Player, ApiController is Connected: " + _apiController.IsConnected);
if (_apiController.IsConnected) if (_apiController.IsConnected)
{ {
ApiController_Connected(null, EventArgs.Empty); ApiControllerOnConnected();
} }
} }
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(PlayerManager)); Logger.Verbose("Disposing " + nameof(PlayerManager));
_apiController.Connected -= ApiController_Connected; _apiController.Connected -= ApiControllerOnConnected;
_apiController.Disconnected -= ApiController_Disconnected; _apiController.Disconnected -= ApiController_Disconnected;
_ipcManager.PenumbraRedrawEvent -= IpcManager_PenumbraRedrawEvent; _ipcManager.PenumbraRedrawEvent -= IpcManager_PenumbraRedrawEvent;
@@ -73,7 +73,7 @@ namespace MareSynchronos.Managers
_lastPlayerObjectCheck = DateTime.Now; _lastPlayerObjectCheck = DateTime.Now;
} }
private void ApiController_Connected(object? sender, EventArgs args) private void ApiControllerOnConnected()
{ {
Logger.Debug("ApiController Connected"); Logger.Debug("ApiController Connected");
@@ -84,17 +84,19 @@ namespace MareSynchronos.Managers
PlayerChanged(); PlayerChanged();
} }
private void ApiController_Disconnected(object? sender, EventArgs args) private void ApiController_Disconnected()
{ {
Logger.Debug(nameof(ApiController_Disconnected)); Logger.Debug(nameof(ApiController_Disconnected));
_ipcManager.PenumbraRedrawEvent -= IpcManager_PenumbraRedrawEvent; _ipcManager.PenumbraRedrawEvent -= IpcManager_PenumbraRedrawEvent;
_dalamudUtil.FrameworkUpdate -= DalamudUtilOnFrameworkUpdate; _dalamudUtil.FrameworkUpdate -= DalamudUtilOnFrameworkUpdate;
LastSentCharacterData = null;
} }
private async Task<CharacterData> CreateFullCharacterCache(CancellationToken token) private async Task<CharacterCacheDto?> CreateFullCharacterCache(CancellationToken token)
{ {
var cache = _characterDataFactory.BuildCharacterData(); var cache = _characterDataFactory.BuildCharacterData();
CharacterCacheDto? cacheDto = null;
await Task.Run(async () => await Task.Run(async () =>
{ {
@@ -105,12 +107,13 @@ namespace MareSynchronos.Managers
if (token.IsCancellationRequested) return; if (token.IsCancellationRequested) return;
var json = JsonConvert.SerializeObject(cache, Formatting.Indented); cacheDto = cache.ToCharacterCacheDto();
var json = JsonConvert.SerializeObject(cacheDto);
cache.CacheHash = Crypto.GetHash(json); cacheDto.Hash = Crypto.GetHash(json);
}, token); }, token);
return cache; return cacheDto;
} }
private void IpcManager_PenumbraRedrawEvent(object? objectTableIndex, EventArgs e) private void IpcManager_PenumbraRedrawEvent(object? objectTableIndex, EventArgs e)
@@ -160,32 +163,21 @@ namespace MareSynchronos.Managers
if (attempts == 10 || token.IsCancellationRequested) return; if (attempts == 10 || token.IsCancellationRequested) return;
Stopwatch st = Stopwatch.StartNew();
_dalamudUtil.WaitWhileSelfIsDrawing(token); _dalamudUtil.WaitWhileSelfIsDrawing(token);
var characterCache = await CreateFullCharacterCache(token); var characterCache = (await CreateFullCharacterCache(token))!;
if (token.IsCancellationRequested) return; if (token.IsCancellationRequested) return;
var cacheDto = characterCache.ToCharacterCacheDto(); if (characterCache.Hash == (LastSentCharacterData?.Hash ?? "-"))
st.Stop();
if (token.IsCancellationRequested)
{
return;
}
Logger.Debug("Elapsed time PlayerChangedTask: " + st.Elapsed);
if (cacheDto.Hash == (LastSentCharacterData?.CacheHash ?? "-"))
{ {
Logger.Debug("Not sending data, already sent"); Logger.Debug("Not sending data, already sent");
return; return;
} }
LastSentCharacterData = characterCache; LastSentCharacterData = characterCache;
PlayerHasChanged?.Invoke(cacheDto); PlayerHasChanged?.Invoke(characterCache);
SendingData = false; SendingData = false;
}, token); }, token);
} }

View File

@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<Authors></Authors> <Authors></Authors>
<Company></Company> <Company></Company>
<Version>0.0.0.1</Version> <Version>0.0.2.0</Version>
<Description></Description> <Description></Description>
<Copyright></Copyright> <Copyright></Copyright>
<PackageProjectUrl>https://github.com/Penumbra-Sync/client</PackageProjectUrl> <PackageProjectUrl>https://github.com/Penumbra-Sync/client</PackageProjectUrl>
@@ -71,10 +71,13 @@
<None Update="FileCache.db"> <None Update="FileCache.db">
<CopyToOutputDirectory>Never</CopyToOutputDirectory> <CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None> </None>
<None Update="images\icon.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\alpine-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-arm&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-arm64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-armel&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-mips64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-musl-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-x86&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\osx-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\win-arm&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\win-arm64&#xD;&#xA;del /Q $(ProjectDir)$(OutDir)Mare.7z&#xD;&#xA;&quot;C:\Program Files\7-zip\7z.exe&quot; a $(ProjectDir)$(OutDir)Mare.7z $(ProjectDir)$(OutDir)*" /> <Exec Command="rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\alpine-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-arm&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-arm64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-armel&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-mips64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-musl-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\linux-x86&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\osx-x64&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\win-arm&#xD;&#xA;rmdir /S /Q $(ProjectDir)$(OutDir)runtimes\win-arm64&#xD;&#xA;if $(ConfigurationName) == Debug (&#xD;&#xA;del /Q $(ProjectDir)$(OutDir)Mare.7z&#xD;&#xA;&quot;C:\Program Files\7-zip\7z.exe&quot; a $(ProjectDir)$(OutDir)Mare.7z $(ProjectDir)$(OutDir)*&#xD;&#xA;)" />
</Target> </Target>
</Project> </Project>

View File

@@ -2,13 +2,11 @@
"Author": "darkarchon", "Author": "darkarchon",
"Name": "Mare Synchronos", "Name": "Mare Synchronos",
"Punchline": "Let others see you as you see yourself.", "Punchline": "Let others see you as you see yourself.",
"Description": "", "Description": "This plugin will synchronize your Penumbra mods and current Glamourer state with other paired clients automatically.",
"InternalName": "mareSynchronos", "InternalName": "mareSynchronos",
"ApplicableVersion": "any", "ApplicableVersion": "any",
"Tags": [ "Tags": [
"sample", "customization"
"plugin",
"goats"
], ],
"IconUrl": "https://raw.githubusercontent.com/Penumbra-Sync/client/main/MareSynchronos/images/logo.png", "IconUrl": "https://raw.githubusercontent.com/Penumbra-Sync/client/main/MareSynchronos/images/logo.png",
"RepoUrl": "https://github.com/Penumbra-Sync/client" "RepoUrl": "https://github.com/Penumbra-Sync/client"

View File

@@ -9,20 +9,6 @@ namespace MareSynchronos.Models
[JsonObject(MemberSerialization.OptIn)] [JsonObject(MemberSerialization.OptIn)]
public class CharacterData public class CharacterData
{ {
[JsonProperty]
public List<FileReplacement> AllReplacements => FileReplacements.Where(f => f.HasFileReplacement).GroupBy(f => f.Hash).Select(g =>
{
return new FileReplacement("")
{
ResolvedPath = g.First().ResolvedPath,
GamePaths = g.SelectMany(g => g.GamePaths).Distinct().ToList(),
Hash = g.First().Hash
};
}).ToList();
[JsonProperty]
public string CacheHash { get; set; } = string.Empty;
public List<FileReplacement> FileReplacements { get; set; } = new(); public List<FileReplacement> FileReplacements { get; set; } = new();
[JsonProperty] [JsonProperty]
@@ -54,9 +40,15 @@ namespace MareSynchronos.Models
{ {
return new CharacterCacheDto() return new CharacterCacheDto()
{ {
FileReplacements = AllReplacements.Select(f => f.ToFileReplacementDto()).ToList(), FileReplacements = FileReplacements.Where(f => f.HasFileReplacement).GroupBy(f => f.Hash).Select(g =>
{
return new FileReplacementDto()
{
GamePaths = g.SelectMany(g => g.GamePaths).Distinct().ToArray(),
Hash = g.First().Hash
};
}).ToList(),
GlamourerData = GlamourerString, GlamourerData = GlamourerString,
Hash = CacheHash,
JobId = JobId, JobId = JobId,
ManipulationData = ManipulationString ManipulationData = ManipulationString
}; };

View File

@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json;
using MareSynchronos.FileCacheDB; using MareSynchronos.FileCacheDB;
using System.IO; using System.IO;
using MareSynchronos.API; using MareSynchronos.API;
@@ -12,29 +11,23 @@ using MareSynchronos.Utils;
namespace MareSynchronos.Models namespace MareSynchronos.Models
{ {
[JsonObject(MemberSerialization.OptIn)]
public class FileReplacement public class FileReplacement
{ {
private readonly string _penumbraDirectory; private readonly string _penumbraDirectory;
private Task? _computationTask = null;
public FileReplacement(string penumbraDirectory) public FileReplacement(string penumbraDirectory)
{ {
this._penumbraDirectory = penumbraDirectory; _penumbraDirectory = penumbraDirectory;
} }
public bool Computed => (_computationTask == null || (_computationTask?.IsCompleted ?? true)); public bool Computed => !HasFileReplacement || !string.IsNullOrEmpty(Hash);
[JsonProperty]
public List<string> GamePaths { get; set; } = new(); public List<string> GamePaths { get; set; } = new();
public bool HasFileReplacement => GamePaths.Count >= 1 && GamePaths.Any(p => p != ResolvedPath); public bool HasFileReplacement => GamePaths.Count >= 1 && GamePaths.Any(p => p != ResolvedPath);
[JsonProperty]
public string Hash { get; set; } = string.Empty; public string Hash { get; set; } = string.Empty;
[JsonProperty]
public string ResolvedPath { get; set; } = string.Empty; public string ResolvedPath { get; set; } = string.Empty;
public void SetResolvedPath(string path) public void SetResolvedPath(string path)
@@ -42,7 +35,7 @@ namespace MareSynchronos.Models
ResolvedPath = path.ToLower().Replace('/', '\\').Replace(_penumbraDirectory, "").Replace('\\', '/'); ResolvedPath = path.ToLower().Replace('/', '\\').Replace(_penumbraDirectory, "").Replace('\\', '/');
if (!HasFileReplacement) return; if (!HasFileReplacement) return;
_computationTask = Task.Run(() => _ = Task.Run(() =>
{ {
FileCache? fileCache; FileCache? fileCache;
using (FileCacheContext db = new()) using (FileCacheContext db = new())

View File

@@ -11,6 +11,7 @@ using Dalamud.Interface.ImGuiFileDialog;
using MareSynchronos.Managers; using MareSynchronos.Managers;
using MareSynchronos.WebAPI; using MareSynchronos.WebAPI;
using Dalamud.Interface.Windowing; using Dalamud.Interface.Windowing;
using Dalamud.Logging;
using MareSynchronos.UI; using MareSynchronos.UI;
using MareSynchronos.Utils; using MareSynchronos.Utils;
@@ -81,7 +82,7 @@ namespace MareSynchronos
_dalamudUtil.LogIn += DalamudUtilOnLogIn; _dalamudUtil.LogIn += DalamudUtilOnLogIn;
_dalamudUtil.LogOut += DalamudUtilOnLogOut; _dalamudUtil.LogOut += DalamudUtilOnLogOut;
_apiController.ChangingServers += ApiControllerOnChangingServers; _apiController.RegisterFinalized += ApiControllerOnRegisterFinalized;
if (_dalamudUtil.IsLoggedIn) if (_dalamudUtil.IsLoggedIn)
{ {
@@ -89,7 +90,7 @@ namespace MareSynchronos
} }
} }
private void ApiControllerOnChangingServers(object? sender, EventArgs e) private void ApiControllerOnRegisterFinalized()
{ {
_mainUi.IsOpen = false; _mainUi.IsOpen = false;
_introUi.IsOpen = true; _introUi.IsOpen = true;
@@ -98,8 +99,8 @@ namespace MareSynchronos
public string Name => "Mare Synchronos"; public string Name => "Mare Synchronos";
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + Name); Logger.Verbose("Disposing " + Name);
_apiController.ChangingServers -= ApiControllerOnChangingServers; _apiController.RegisterFinalized -= ApiControllerOnRegisterFinalized;
_apiController?.Dispose(); _apiController?.Dispose();
_commandManager.RemoveHandler(CommandName); _commandManager.RemoveHandler(CommandName);
@@ -114,6 +115,7 @@ namespace MareSynchronos
_ipcManager?.Dispose(); _ipcManager?.Dispose();
_playerManager?.Dispose(); _playerManager?.Dispose();
_characterCacheManager?.Dispose(); _characterCacheManager?.Dispose();
PluginLog.Information("Shut down");
} }

View File

@@ -17,13 +17,13 @@ public class DownloadUi : Window, IDisposable
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(DownloadUi)); Logger.Verbose("Disposing " + nameof(DownloadUi));
_windowSystem.RemoveWindow(this); _windowSystem.RemoveWindow(this);
} }
public DownloadUi(WindowSystem windowSystem, Configuration pluginConfiguration, ApiController apiController, UiShared uiShared) : base("Mare Synchronos Downloads") public DownloadUi(WindowSystem windowSystem, Configuration pluginConfiguration, ApiController apiController, UiShared uiShared) : base("Mare Synchronos Downloads")
{ {
Logger.Debug("Creating " + nameof(DownloadUi)); Logger.Verbose("Creating " + nameof(DownloadUi));
_windowSystem = windowSystem; _windowSystem = windowSystem;
_pluginConfiguration = pluginConfiguration; _pluginConfiguration = pluginConfiguration;
_apiController = apiController; _apiController = apiController;

View File

@@ -20,7 +20,7 @@ namespace MareSynchronos.UI
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(IntroUi)); Logger.Verbose("Disposing " + nameof(IntroUi));
_windowSystem.RemoveWindow(this); _windowSystem.RemoveWindow(this);
} }
@@ -28,7 +28,7 @@ namespace MareSynchronos.UI
public IntroUi(WindowSystem windowSystem, UiShared uiShared, Configuration pluginConfiguration, public IntroUi(WindowSystem windowSystem, UiShared uiShared, Configuration pluginConfiguration,
FileCacheManager fileCacheManager) : base("Mare Synchronos Setup") FileCacheManager fileCacheManager) : base("Mare Synchronos Setup")
{ {
Logger.Debug("Creating " + nameof(IntroUi)); Logger.Verbose("Creating " + nameof(IntroUi));
_uiShared = uiShared; _uiShared = uiShared;
_pluginConfiguration = pluginConfiguration; _pluginConfiguration = pluginConfiguration;
@@ -61,10 +61,9 @@ namespace MareSynchronos.UI
"Note that you will have to have Penumbra as well as Glamourer installed to use this plugin."); "Note that you will have to have Penumbra as well as Glamourer installed to use this plugin.");
UiShared.TextWrapped("We will have to setup a few things first before you can start using this plugin. Click on next to continue."); UiShared.TextWrapped("We will have to setup a few things first before you can start using this plugin. Click on next to continue.");
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); UiShared.ColorTextWrapped("Note: Any modifications you have applied through anything but Penumbra cannot be shared and your character state on other clients " +
UiShared.TextWrapped("Note: Any modifications you have applied through anything but Penumbra cannot be shared and your character state on other clients " + "might look broken because of this or others players mods might not apply on your end altogether. " +
"might look broken because of this. If you want to use this plugin you will have to move your mods to Penumbra."); "If you want to use this plugin you will have to move your mods to Penumbra.", ImGuiColors.DalamudYellow);
ImGui.PopStyleColor();
if (!_uiShared.DrawOtherPluginState()) return; if (!_uiShared.DrawOtherPluginState()) return;
ImGui.Separator(); ImGui.Separator();
if (ImGui.Button("Next##toAgreement")) if (ImGui.Button("Next##toAgreement"))
@@ -90,22 +89,16 @@ namespace MareSynchronos.UI
UiShared.TextWrapped("If you are on a data capped internet connection, higher fees due to data usage depending on the amount of downloaded and uploaded mod files might occur. " + UiShared.TextWrapped("If you are on a data capped internet connection, higher fees due to data usage depending on the amount of downloaded and uploaded mod files might occur. " +
"Mod files will be compressed on up- and download to save on bandwidth usage. Due to varying up- and download speeds, changes in characters might not be visible immediately. " + "Mod files will be compressed on up- and download to save on bandwidth usage. Due to varying up- and download speeds, changes in characters might not be visible immediately. " +
"Files present on the service that already represent your active mod files will not be uploaded again."); "Files present on the service that already represent your active mod files will not be uploaded again.");
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); UiShared.ColorTextWrapped("The mod files you are uploading are confidential and will not be distributed to parties other than the ones who are requesting the exact same mod files. " +
UiShared.TextWrapped("The mod files you are uploading are confidential and will not be distributed to parties other than the ones who are requesting the exact same mod files. " +
"Please think about who you are going to pair since it is unavoidable that they will receive and locally cache the necessary mod files that you have currently in use. " + "Please think about who you are going to pair since it is unavoidable that they will receive and locally cache the necessary mod files that you have currently in use. " +
"Locally cached mod files will have arbitrary file names to discourage attempts at replicating the original mod."); "Locally cached mod files will have arbitrary file names to discourage attempts at replicating the original mod.", ImGuiColors.DalamudRed);
ImGui.PopStyleColor(); UiShared.ColorTextWrapped("The plugin creator tried their best to keep you secure. However, there is no guarantee for 100% security. Do not blindly pair your client with everyone.", ImGuiColors.DalamudYellow);
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow);
UiShared.TextWrapped("The plugin creator tried their best to keep you secure. However, there is no guarantee for 100% security. Do not blindly pair your client with everyone.");
ImGui.PopStyleColor();
UiShared.TextWrapped("Mod files that are saved on the service will remain on the service as long as there are requests for the files from clients. " + UiShared.TextWrapped("Mod files that are saved on the service will remain on the service as long as there are requests for the files from clients. " +
"After a period of not being used, the mod files will be automatically deleted. " + "After a period of not being used, the mod files will be automatically deleted. " +
"You will also be able to wipe all the files you have personally uploaded on request. " + "You will also be able to wipe all the files you have personally uploaded on request. " +
"The service holds no information about which mod files belong to which mod."); "The service holds no information about which mod files belong to which mod.");
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); UiShared.ColorTextWrapped("This service is provided as-is. In case of abuse, contact darkarchon#4313 on Discord or join the Mare Synchronos Discord. " +
UiShared.TextWrapped("This service is provided as-is. In case of abuse, contact darkarchon#4313 on Discord or join the Mare Synchronos Discord. " + "To accept those conditions hold CTRL while clicking 'I agree'", ImGuiColors.DalamudRed);
"To accept those conditions hold CTRL while clicking 'I agree'");
ImGui.PopStyleColor();
ImGui.Separator(); ImGui.Separator();
if (ImGui.Button("I agree##toSetup")) if (ImGui.Button("I agree##toSetup"))

View File

@@ -27,7 +27,7 @@ namespace MareSynchronos.UI
public MainUi(WindowSystem windowSystem, public MainUi(WindowSystem windowSystem,
UiShared uiShared, Configuration configuration, ApiController apiController) : base("Mare Synchronos Settings", ImGuiWindowFlags.None) UiShared uiShared, Configuration configuration, ApiController apiController) : base("Mare Synchronos Settings", ImGuiWindowFlags.None)
{ {
Logger.Debug("Creating " + nameof(MainUi)); Logger.Verbose("Creating " + nameof(MainUi));
SizeConstraints = new WindowSizeConstraints() SizeConstraints = new WindowSizeConstraints()
{ {
@@ -44,7 +44,7 @@ namespace MareSynchronos.UI
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(MainUi)); Logger.Verbose("Disposing " + nameof(MainUi));
_windowSystem.RemoveWindow(this); _windowSystem.RemoveWindow(this);
} }
@@ -66,11 +66,12 @@ namespace MareSynchronos.UI
{ {
_uiShared.PrintServerState(); _uiShared.PrintServerState();
ImGui.Separator(); ImGui.Separator();
ImGui.SetWindowFontScale(1.2f);
ImGui.Text("Your UID"); if (_apiController.ServerState is ServerState.Connected)
ImGui.SameLine();
if (_apiController.IsConnected)
{ {
ImGui.SetWindowFontScale(1.2f);
ImGui.Text("Your UID");
ImGui.SameLine();
ImGui.TextColored(ImGuiColors.ParsedGreen, _apiController.UID); ImGui.TextColored(ImGuiColors.ParsedGreen, _apiController.UID);
ImGui.SameLine(); ImGui.SameLine();
ImGui.SetWindowFontScale(1.0f); ImGui.SetWindowFontScale(1.0f);
@@ -83,33 +84,44 @@ namespace MareSynchronos.UI
} }
else else
{ {
var error = _configuration.FullPause ? "Disconnected" string errorMsg = _apiController.ServerState switch
: !_apiController.ServerAlive {
? "Service unavailable" ServerState.Disconnected => "Disconnected",
: !_apiController.ServerSupportsThisClient ServerState.Unauthorized => "Unauthorized",
? "Service version mismatch" ServerState.VersionMisMatch => "Service version mismatch",
: "Unauthorized"; ServerState.Offline => "Service unavailable"
ImGui.TextColored(ImGuiColors.DalamudRed, $"No UID ({error})"); };
ImGui.SetWindowFontScale(1.2f);
ImGui.TextColored(ImGuiColors.DalamudRed, $"No UID ({errorMsg})");
ImGui.SetWindowFontScale(1.0f); ImGui.SetWindowFontScale(1.0f);
if (_apiController.ServerAlive && !_configuration.FullPause && _apiController.ServerSupportsThisClient) switch (_apiController.ServerState)
{ {
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); case ServerState.Disconnected:
UiShared.TextWrapped("Your account is not present on the service anymore or you are banned."); UiShared.ColorTextWrapped("You are currently disconnected from the Mare Synchronos service.", ImGuiColors.DalamudRed);
ImGui.PopStyleColor(); break;
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); case ServerState.Unauthorized:
UiShared.TextWrapped("If you think your secret key is just invalid, use the following button to reset the local secret key to be able to re-register. If you continue to see this message after registering, tough luck, asshole."); UiShared.ColorTextWrapped("Your account is not present on the service anymore or you are banned.", ImGuiColors.DalamudRed);
ImGui.PopStyleColor(); UiShared.ColorTextWrapped("If you think your secret key is just invalid, use the following button to reset " +
if (ImGui.Button("Reset Secret Key")) "the local secret key to be able to re-register. If you continue to see this message after " +
{ "registering, tough luck, asshole.", ImGuiColors.DalamudYellow);
_configuration.ClientSecret.Remove(_configuration.ApiUri); if (ImGui.Button("Reset Secret Key"))
_configuration.Save(); {
SwitchFromMainUiToIntro?.Invoke(); _configuration.ClientSecret.Remove(_configuration.ApiUri);
} _configuration.Save();
} else if (!_apiController.ServerSupportsThisClient) SwitchFromMainUiToIntro?.Invoke();
{ }
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); break;
UiShared.TextWrapped("The server or your client is outdated. If the client has recently been updated for breaking service changes, the service must follow suit."); case ServerState.Offline:
ImGui.PopStyleColor(); UiShared.ColorTextWrapped("Your selected Mare Synchronos server is currently offline.", ImGuiColors.DalamudRed);
break;
case ServerState.VersionMisMatch:
UiShared.ColorTextWrapped("The server or your client is outdated. If the client has recently been updated for breaking " +
"service changes, the service must follow suit.", ImGuiColors.DalamudRed);
break;
case ServerState.Connected:
default:
break;
} }
} }
@@ -465,9 +477,7 @@ namespace MareSynchronos.UI
if (!_configuration.FullPause) if (!_configuration.FullPause)
{ {
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); UiShared.ColorTextWrapped("Note: to change servers you need to disconnect from your current Mare Synchronos server.", ImGuiColors.DalamudYellow);
UiShared.TextWrapped("Note: to change servers you need to disconnect from your current Mare Synchronos server.");
ImGui.PopStyleColor();
} }
var marePaused = _configuration.FullPause; var marePaused = _configuration.FullPause;
@@ -485,18 +495,14 @@ namespace MareSynchronos.UI
} }
else else
{ {
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); UiShared.ColorText("You cannot reconnect without a valid account on the service.", ImGuiColors.DalamudYellow);
ImGui.TextUnformatted("You cannot reconnect without a valid account on the service.");
ImGui.PopStyleColor();
} }
if (marePaused) if (marePaused)
{ {
_uiShared.DrawServiceSelection(() => SwitchFromMainUiToIntro?.Invoke()); _uiShared.DrawServiceSelection(() => SwitchFromMainUiToIntro?.Invoke());
} }
ImGui.TreePop(); ImGui.TreePop();
} }
} }
@@ -506,11 +512,10 @@ namespace MareSynchronos.UI
if (ImGui.TreeNode( if (ImGui.TreeNode(
$"Forbidden Transfers")) $"Forbidden Transfers"))
{ {
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudGrey); UiShared.ColorTextWrapped("Files that you attempted to upload or download that were forbidden to be transferred by their creators will appear here. " +
UiShared.TextWrapped("Files that you attempted to upload or download that were forbidden to be transferred by their creators will appear here. " +
"If you see file paths from your drive here, then those files were not allowed to be uploaded. If you see hashes, those files were not allowed to be downloaded. " + "If you see file paths from your drive here, then those files were not allowed to be uploaded. If you see hashes, those files were not allowed to be downloaded. " +
"Ask your paired friend to send you the mod in question through other means, acquire the mod yourself or pester the mod creator to allow it to be sent over Mare."); "Ask your paired friend to send you the mod in question through other means, acquire the mod yourself or pester the mod creator to allow it to be sent over Mare.",
ImGui.PopStyleColor(); ImGuiColors.DalamudGrey);
if (ImGui.BeginTable("TransfersTable", 2, ImGuiTableFlags.SizingStretchProp)) if (ImGui.BeginTable("TransfersTable", 2, ImGuiTableFlags.SizingStretchProp))
{ {
@@ -579,7 +584,7 @@ namespace MareSynchronos.UI
ImGui.TableSetupColumn("Uploaded"); ImGui.TableSetupColumn("Uploaded");
ImGui.TableSetupColumn("Size"); ImGui.TableSetupColumn("Size");
ImGui.TableHeadersRow(); ImGui.TableHeadersRow();
foreach (var transfer in _apiController.CurrentUploads) foreach (var transfer in _apiController.CurrentUploads.ToArray())
{ {
var color = UiShared.UploadColor((transfer.Transferred, transfer.Total)); var color = UiShared.UploadColor((transfer.Transferred, transfer.Total));
ImGui.PushStyleColor(ImGuiCol.Text, color); ImGui.PushStyleColor(ImGuiCol.Text, color);
@@ -603,7 +608,7 @@ namespace MareSynchronos.UI
ImGui.TableSetupColumn("Downloaded"); ImGui.TableSetupColumn("Downloaded");
ImGui.TableSetupColumn("Size"); ImGui.TableSetupColumn("Size");
ImGui.TableHeadersRow(); ImGui.TableHeadersRow();
foreach (var transfer in _apiController.CurrentDownloads) foreach (var transfer in _apiController.CurrentDownloads.ToArray())
{ {
var color = UiShared.UploadColor((transfer.Transferred, transfer.Total)); var color = UiShared.UploadColor((transfer.Transferred, transfer.Total));
ImGui.PushStyleColor(ImGuiCol.Text, color); ImGui.PushStyleColor(ImGuiCol.Text, color);

View File

@@ -34,7 +34,7 @@ namespace MareSynchronos.UI
_fileDialogManager = fileDialogManager; _fileDialogManager = fileDialogManager;
_pluginConfiguration = pluginConfiguration; _pluginConfiguration = pluginConfiguration;
_dalamudUtil = dalamudUtil; _dalamudUtil = dalamudUtil;
isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder); _isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder);
} }
public bool DrawOtherPluginState() public bool DrawOtherPluginState()
@@ -85,7 +85,7 @@ namespace MareSynchronos.UI
var serverName = _apiController.ServerDictionary.ContainsKey(_pluginConfiguration.ApiUri) var serverName = _apiController.ServerDictionary.ContainsKey(_pluginConfiguration.ApiUri)
? _apiController.ServerDictionary[_pluginConfiguration.ApiUri] ? _apiController.ServerDictionary[_pluginConfiguration.ApiUri]
: _pluginConfiguration.ApiUri; : _pluginConfiguration.ApiUri;
ImGui.Text("Service " + serverName + ":"); ImGui.TextUnformatted("Service " + serverName + ":");
ImGui.SameLine(); ImGui.SameLine();
var color = _apiController.ServerAlive ? ImGuiColors.ParsedGreen : ImGuiColors.DalamudRed; var color = _apiController.ServerAlive ? ImGuiColors.ParsedGreen : ImGuiColors.DalamudRed;
ImGui.TextColored(color, _apiController.ServerAlive ? "Available" : "Unavailable"); ImGui.TextColored(color, _apiController.ServerAlive ? "Available" : "Unavailable");
@@ -102,6 +102,20 @@ namespace MareSynchronos.UI
} }
} }
public static void ColorText(string text, Vector4 color)
{
ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGui.TextUnformatted(text);
ImGui.PopStyleColor();
}
public static void ColorTextWrapped(string text, Vector4 color)
{
ImGui.PushStyleColor(ImGuiCol.Text, color);
TextWrapped(text);
ImGui.PopStyleColor();
}
public static void TextWrapped(string text) public static void TextWrapped(string text)
{ {
ImGui.PushTextWrapPos(0); ImGui.PushTextWrapPos(0);
@@ -238,9 +252,7 @@ namespace MareSynchronos.UI
} }
else else
{ {
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); ColorTextWrapped("You already have an account on this server.", ImGuiColors.DalamudYellow);
TextWrapped("You already have an account on this server.");
ImGui.PopStyleColor();
ImGui.SameLine(); ImGui.SameLine();
if (ImGui.Button("Connect##connectToService")) if (ImGui.Button("Connect##connectToService"))
{ {
@@ -301,7 +313,7 @@ namespace MareSynchronos.UI
_pluginConfiguration.CacheFolder = cacheDirectory; _pluginConfiguration.CacheFolder = cacheDirectory;
if (!string.IsNullOrEmpty(_pluginConfiguration.CacheFolder) if (!string.IsNullOrEmpty(_pluginConfiguration.CacheFolder)
&& Directory.Exists(_pluginConfiguration.CacheFolder) && Directory.Exists(_pluginConfiguration.CacheFolder)
&& (isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder))) && (_isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder)))
{ {
_pluginConfiguration.Save(); _pluginConfiguration.Save();
_fileCacheManager.StartWatchers(); _fileCacheManager.StartWatchers();
@@ -318,8 +330,8 @@ namespace MareSynchronos.UI
if (!success) return; if (!success) return;
_pluginConfiguration.CacheFolder = path; _pluginConfiguration.CacheFolder = path;
isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder); _isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder);
if (isDirectoryWritable) if (_isDirectoryWritable)
{ {
_pluginConfiguration.Save(); _pluginConfiguration.Save();
_fileCacheManager.StartWatchers(); _fileCacheManager.StartWatchers();
@@ -328,15 +340,13 @@ namespace MareSynchronos.UI
} }
ImGui.PopFont(); ImGui.PopFont();
if (!Directory.Exists(cacheDirectory) || !isDirectoryWritable) if (!Directory.Exists(cacheDirectory) || !_isDirectoryWritable)
{ {
ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); ColorTextWrapped("The folder you selected does not exist or cannot be written to. Please provide a valid path.", ImGuiColors.DalamudRed);
TextWrapped("The folder you selected does not exist or cannot be written to. Please provide a valid path.");
ImGui.PopStyleColor();
} }
} }
private bool isDirectoryWritable = false; private bool _isDirectoryWritable = false;
public bool IsDirectoryWritable(string dirPath, bool throwIfFails = false) public bool IsDirectoryWritable(string dirPath, bool throwIfFails = false)
{ {

View File

@@ -17,12 +17,6 @@ namespace MareSynchronos.WebAPI
await CreateConnections(); await CreateConnections();
} }
public async Task GetCharacterData(Dictionary<string, int> hashedCharacterNames)
{
await _userHub!.InvokeAsync("GetCharacterData",
hashedCharacterNames);
}
public async Task Register() public async Task Register()
{ {
if (!ServerAlive) return; if (!ServerAlive) return;
@@ -30,7 +24,7 @@ namespace MareSynchronos.WebAPI
var response = await _userHub!.InvokeAsync<string>("Register"); var response = await _userHub!.InvokeAsync<string>("Register");
_pluginConfiguration.ClientSecret[ApiUri] = response; _pluginConfiguration.ClientSecret[ApiUri] = response;
_pluginConfiguration.Save(); _pluginConfiguration.Save();
ChangingServers?.Invoke(null, EventArgs.Empty); RegisterFinalized?.Invoke();
await CreateConnections(); await CreateConnections();
} }

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
@@ -13,21 +12,32 @@ using Microsoft.AspNetCore.SignalR.Client;
namespace MareSynchronos.WebAPI namespace MareSynchronos.WebAPI
{ {
public delegate void VoidDelegate();
public delegate void SimpleStringDelegate(string str);
public enum ServerState
{
Offline,
Disconnected,
Connected,
Unauthorized,
VersionMisMatch
}
public partial class ApiController : IDisposable public partial class ApiController : IDisposable
{ {
#if DEBUG #if DEBUG
public const string MainServer = "darkarchons Debug Server (Dev Server (CH))"; public const string MainServer = "Lunae Crescere Incipientis (Central Server EU)";
public const string MainServiceUri = "wss://darkarchon.internet-box.ch:5000"; public const string MainServiceUri = "wss://v2202207178628194299.powersrv.de:6871";
public readonly int[] SupportedServerVersions = { 1 };
#else #else
public const string MainServer = "Lunae Crescere Incipientis (Central Server EU)"; public const string MainServer = "Lunae Crescere Incipientis (Central Server EU)";
public const string MainServiceUri = "to be defined"; public const string MainServiceUri = "wss://v2202207178628194299.powersrv.de:6871";
#endif #endif
public readonly int[] SupportedServerVersions = { 1 };
private readonly Configuration _pluginConfiguration; private readonly Configuration _pluginConfiguration;
private readonly DalamudUtil _dalamudUtil; private readonly DalamudUtil _dalamudUtil;
private CancellationTokenSource _cts; private CancellationTokenSource _connectionCancellationTokenSource;
private HubConnection? _fileHub; private HubConnection? _fileHub;
@@ -45,11 +55,11 @@ namespace MareSynchronos.WebAPI
public ApiController(Configuration pluginConfiguration, DalamudUtil dalamudUtil) public ApiController(Configuration pluginConfiguration, DalamudUtil dalamudUtil)
{ {
Logger.Debug("Creating " + nameof(ApiController)); Verbose.Debug("Creating " + nameof(ApiController));
_pluginConfiguration = pluginConfiguration; _pluginConfiguration = pluginConfiguration;
_dalamudUtil = dalamudUtil; _dalamudUtil = dalamudUtil;
_cts = new CancellationTokenSource(); _connectionCancellationTokenSource = new CancellationTokenSource();
_dalamudUtil.LogIn += DalamudUtilOnLogIn; _dalamudUtil.LogIn += DalamudUtilOnLogIn;
_dalamudUtil.LogOut += DalamudUtilOnLogOut; _dalamudUtil.LogOut += DalamudUtilOnLogOut;
@@ -61,7 +71,7 @@ namespace MareSynchronos.WebAPI
private void DalamudUtilOnLogOut() private void DalamudUtilOnLogOut()
{ {
Task.Run(async () => await StopAllConnections(_cts.Token)); Task.Run(async () => await StopAllConnections(_connectionCancellationTokenSource.Token));
} }
private void DalamudUtilOnLogIn() private void DalamudUtilOnLogIn()
@@ -70,21 +80,21 @@ namespace MareSynchronos.WebAPI
} }
public event EventHandler? ChangingServers;
public event EventHandler<CharacterReceivedEventArgs>? CharacterReceived; public event EventHandler<CharacterReceivedEventArgs>? CharacterReceived;
public event EventHandler? Connected; public event VoidDelegate? RegisterFinalized;
public event EventHandler? Disconnected; public event VoidDelegate? Connected;
public event EventHandler? PairedClientOffline; public event VoidDelegate? Disconnected;
public event EventHandler? PairedClientOnline; public event SimpleStringDelegate? PairedClientOffline;
public event EventHandler? PairedWithOther; public event SimpleStringDelegate? PairedClientOnline;
public event EventHandler? UnpairedFromOther; public event SimpleStringDelegate? PairedWithOther;
public event SimpleStringDelegate? UnpairedFromOther;
public List<FileTransfer> CurrentDownloads { get; } = new(); public List<FileTransfer> CurrentDownloads { get; } = new();
@@ -96,7 +106,7 @@ namespace MareSynchronos.WebAPI
public List<ForbiddenFileDto> AdminForbiddenFiles { get; private set; } = new(); public List<ForbiddenFileDto> AdminForbiddenFiles { get; private set; } = new();
public bool IsConnected => !string.IsNullOrEmpty(UID) && ServerSupportsThisClient; public bool IsConnected => ServerState == ServerState.Connected;
public bool IsDownloading => CurrentDownloads.Count > 0; public bool IsDownloading => CurrentDownloads.Count > 0;
@@ -104,33 +114,51 @@ namespace MareSynchronos.WebAPI
public List<ClientPairDto> PairedClients { get; set; } = new(); public List<ClientPairDto> PairedClients { get; set; } = new();
public string SecretKey => _pluginConfiguration.ClientSecret.ContainsKey(ApiUri) ? _pluginConfiguration.ClientSecret[ApiUri] : "-"; public string SecretKey => _pluginConfiguration.ClientSecret.ContainsKey(ApiUri)
? _pluginConfiguration.ClientSecret[ApiUri]
: "-";
public bool ServerAlive => public bool ServerAlive =>
(_heartbeatHub?.State ?? HubConnectionState.Disconnected) == HubConnectionState.Connected; (_heartbeatHub?.State ?? HubConnectionState.Disconnected) == HubConnectionState.Connected;
public bool ServerSupportsThisClient => SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0); public Dictionary<string, string> ServerDictionary => new Dictionary<string, string>()
{ { MainServiceUri, MainServer } }
public Dictionary<string, string> ServerDictionary => new Dictionary<string, string>() { { MainServiceUri, MainServer } }
.Concat(_pluginConfiguration.CustomServerList) .Concat(_pluginConfiguration.CustomServerList)
.ToDictionary(k => k.Key, k => k.Value); .ToDictionary(k => k.Key, k => k.Value);
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 { get; private set; }
public ServerState ServerState
{
get
{
if (_pluginConfiguration.FullPause)
return ServerState.Disconnected;
if (!ServerAlive)
return ServerState.Offline;
if (ServerAlive && !SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0) && !string.IsNullOrEmpty(UID))
return ServerState.VersionMisMatch;
if (ServerAlive && SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0)
&& string.IsNullOrEmpty(UID))
return ServerState.Unauthorized;
return ServerState.Connected;
}
}
public async Task CreateConnections() public async Task CreateConnections()
{ {
await StopAllConnections(_cts.Token); Logger.Verbose("Recreating Connection");
_cts = new CancellationTokenSource(); await StopAllConnections(_connectionCancellationTokenSource.Token);
var token = _cts.Token;
_connectionCancellationTokenSource.Cancel();
_connectionCancellationTokenSource = new CancellationTokenSource();
var token = _connectionCancellationTokenSource.Token;
while (!ServerAlive && !token.IsCancellationRequested) while (!ServerAlive && !token.IsCancellationRequested)
{ {
await StopAllConnections(token);
try try
{ {
if (_dalamudUtil.PlayerCharacter == null) throw new ArgumentException("Player not initialized"); if (_dalamudUtil.PlayerCharacter == null) throw new ArgumentException("Player not initialized");
@@ -147,7 +175,7 @@ namespace MareSynchronos.WebAPI
OnlineUsers = await _userHub.InvokeAsync<int>("GetOnlineUsers", token); OnlineUsers = await _userHub.InvokeAsync<int>("GetOnlineUsers", token);
_userHub.On<int>("UsersOnline", (count) => OnlineUsers = count); _userHub.On<int>("UsersOnline", (count) => OnlineUsers = count);
if (_pluginConfiguration.FullPause) if (_pluginConfiguration.FullPause)
{ {
_connectionDto = null; _connectionDto = null;
@@ -155,16 +183,15 @@ namespace MareSynchronos.WebAPI
} }
_connectionDto = await _heartbeatHub.InvokeAsync<ConnectionDto>("Heartbeat", token); _connectionDto = await _heartbeatHub.InvokeAsync<ConnectionDto>("Heartbeat", token);
if (!string.IsNullOrEmpty(UID) && !token.IsCancellationRequested if (ServerState is ServerState.Connected) // user is authorized && server is legit
&& ServerSupportsThisClient) // user is authorized && server is legit
{ {
Logger.Debug("Initializing data"); Logger.Debug("Initializing data");
_userHub.On<ClientPairDto, string>("UpdateClientPairs", UpdateLocalClientPairsCallback); _userHub.On<ClientPairDto, string>("UpdateClientPairs", UpdateLocalClientPairsCallback);
_userHub.On<CharacterCacheDto, string>("ReceiveCharacterData", ReceiveCharacterDataCallback); _userHub.On<CharacterCacheDto, string>("ReceiveCharacterData", ReceiveCharacterDataCallback);
_userHub.On<string>("RemoveOnlinePairedPlayer", _userHub.On<string>("RemoveOnlinePairedPlayer",
(s) => PairedClientOffline?.Invoke(s, EventArgs.Empty)); (s) => PairedClientOffline?.Invoke(s));
_userHub.On<string>("AddOnlinePairedPlayer", _userHub.On<string>("AddOnlinePairedPlayer",
(s) => PairedClientOnline?.Invoke(s, EventArgs.Empty)); (s) => PairedClientOnline?.Invoke(s));
_adminHub.On("ForcedReconnect", UserForcedReconnectCallback); _adminHub.On("ForcedReconnect", UserForcedReconnectCallback);
PairedClients = await _userHub!.InvokeAsync<List<ClientPairDto>>("GetPairedClients", token); PairedClients = await _userHub!.InvokeAsync<List<ClientPairDto>>("GetPairedClients", token);
@@ -183,7 +210,7 @@ namespace MareSynchronos.WebAPI
_adminHub.On<ForbiddenFileDto>("DeleteForbiddenFile", DeleteForbiddenFileCallback); _adminHub.On<ForbiddenFileDto>("DeleteForbiddenFile", DeleteForbiddenFileCallback);
} }
Connected?.Invoke(this, EventArgs.Empty); Connected?.Invoke();
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -191,6 +218,7 @@ namespace MareSynchronos.WebAPI
Logger.Warn(ex.Message); Logger.Warn(ex.Message);
Logger.Warn(ex.StackTrace ?? string.Empty); Logger.Warn(ex.StackTrace ?? string.Empty);
Logger.Debug("Failed to establish connection, retrying"); Logger.Debug("Failed to establish connection, retrying");
await StopAllConnections(token);
await Task.Delay(TimeSpan.FromSeconds(5), token); await Task.Delay(TimeSpan.FromSeconds(5), token);
} }
} }
@@ -198,12 +226,12 @@ namespace MareSynchronos.WebAPI
public void Dispose() public void Dispose()
{ {
Logger.Debug("Disposing " + nameof(ApiController)); Logger.Verbose("Disposing " + nameof(ApiController));
_dalamudUtil.LogIn -= DalamudUtilOnLogIn; _dalamudUtil.LogIn -= DalamudUtilOnLogIn;
_dalamudUtil.LogOut -= DalamudUtilOnLogOut; _dalamudUtil.LogOut -= DalamudUtilOnLogOut;
Task.Run(async () => await StopAllConnections(_cts.Token)); Task.Run(async () => await StopAllConnections(_connectionCancellationTokenSource.Token));
} }
private HubConnection BuildHubConnection(string hubName) private HubConnection BuildHubConnection(string hubName)
@@ -235,7 +263,7 @@ namespace MareSynchronos.WebAPI
CurrentDownloads.Clear(); CurrentDownloads.Clear();
_uploadCancellationTokenSource?.Cancel(); _uploadCancellationTokenSource?.Cancel();
Logger.Debug("Connection closed"); Logger.Debug("Connection closed");
Disconnected?.Invoke(null, EventArgs.Empty); Disconnected?.Invoke();
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -244,7 +272,7 @@ namespace MareSynchronos.WebAPI
Logger.Debug("Connection restored"); Logger.Debug("Connection restored");
OnlineUsers = _userHub!.InvokeAsync<int>("GetOnlineUsers").Result; OnlineUsers = _userHub!.InvokeAsync<int>("GetOnlineUsers").Result;
_connectionDto = _heartbeatHub!.InvokeAsync<ConnectionDto>("Heartbeat").Result; _connectionDto = _heartbeatHub!.InvokeAsync<ConnectionDto>("Heartbeat").Result;
Connected?.Invoke(this, EventArgs.Empty); Connected?.Invoke();
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -254,12 +282,13 @@ namespace MareSynchronos.WebAPI
CurrentDownloads.Clear(); CurrentDownloads.Clear();
_uploadCancellationTokenSource?.Cancel(); _uploadCancellationTokenSource?.Cancel();
Logger.Debug("Connection closed... Reconnecting"); Logger.Debug("Connection closed... Reconnecting");
Disconnected?.Invoke(null, EventArgs.Empty); Disconnected?.Invoke();
return Task.CompletedTask; return Task.CompletedTask;
} }
private async Task StopAllConnections(CancellationToken token) private async Task StopAllConnections(CancellationToken token)
{ {
Logger.Verbose("Stopping all connections");
if (_heartbeatHub is not null) if (_heartbeatHub is not null)
{ {
await _heartbeatHub.StopAsync(token); await _heartbeatHub.StopAsync(token);

View File

@@ -20,7 +20,7 @@ namespace MareSynchronos.WebAPI
if (dto.IsRemoved) if (dto.IsRemoved)
{ {
PairedClients.RemoveAll(p => p.OtherUID == dto.OtherUID); PairedClients.RemoveAll(p => p.OtherUID == dto.OtherUID);
UnpairedFromOther?.Invoke(characterIdentifier, EventArgs.Empty); UnpairedFromOther?.Invoke(characterIdentifier);
return; return;
} }
if (entry == null) if (entry == null)
@@ -32,7 +32,7 @@ namespace MareSynchronos.WebAPI
if ((entry.IsPausedFromOthers != dto.IsPausedFromOthers || entry.IsSynced != dto.IsSynced || entry.IsPaused != dto.IsPaused) if ((entry.IsPausedFromOthers != dto.IsPausedFromOthers || entry.IsSynced != dto.IsSynced || entry.IsPaused != dto.IsPaused)
&& !dto.IsPaused && dto.IsSynced && !dto.IsPausedFromOthers) && !dto.IsPaused && dto.IsSynced && !dto.IsPausedFromOthers)
{ {
PairedWithOther?.Invoke(characterIdentifier, EventArgs.Empty); PairedWithOther?.Invoke(characterIdentifier);
} }
entry.IsPaused = dto.IsPaused; entry.IsPaused = dto.IsPaused;
@@ -41,7 +41,7 @@ namespace MareSynchronos.WebAPI
if (dto.IsPaused || dto.IsPausedFromOthers || !dto.IsSynced) if (dto.IsPaused || dto.IsPausedFromOthers || !dto.IsSynced)
{ {
UnpairedFromOther?.Invoke(characterIdentifier, EventArgs.Empty); UnpairedFromOther?.Invoke(characterIdentifier);
} }
} }

View File

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 160 KiB