diff --git a/MareSynchronos/Configuration.cs b/MareSynchronos/Configuration.cs index 7e9f0b5..0de804c 100644 --- a/MareSynchronos/Configuration.cs +++ b/MareSynchronos/Configuration.cs @@ -75,7 +75,7 @@ namespace MareSynchronos public Dictionary> UidServerComments { get; set; } = new(); public Dictionary UidComments { get; set; } = new(); - public int Version { get; set; } = 1; + public int Version { get; set; } = 3; public bool ShowTransferWindow { get; set; } = true; @@ -143,6 +143,17 @@ namespace MareSynchronos Version = 2; 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(); + } } } } diff --git a/MareSynchronos/Factories/CharacterDataFactory.cs b/MareSynchronos/Factories/CharacterDataFactory.cs index 2b634b3..95340e0 100644 --- a/MareSynchronos/Factories/CharacterDataFactory.cs +++ b/MareSynchronos/Factories/CharacterDataFactory.cs @@ -22,7 +22,7 @@ public class CharacterDataFactory public CharacterDataFactory(DalamudUtil dalamudUtil, IpcManager ipcManager) { - Logger.Debug("Creating " + nameof(CharacterDataFactory)); + Logger.Verbose("Creating " + nameof(CharacterDataFactory)); _dalamudUtil = dalamudUtil; _ipcManager = ipcManager; @@ -48,8 +48,8 @@ public class CharacterDataFactory var indentation = GetIndentationForInheritanceLevel(inheritanceLevel); objectKind += string.IsNullOrEmpty(objectKind) ? "" : " "; - Logger.Debug(indentation.Item1 + objectKind + resourceType + " [" + string.Join(", ", fileReplacement.GamePaths) + "]"); - Logger.Debug(indentation.Item2 + "=> " + fileReplacement.ResolvedPath); + Logger.Verbose(indentation.Item1 + objectKind + resourceType + " [" + string.Join(", ", fileReplacement.GamePaths) + "]"); + Logger.Verbose(indentation.Item2 + "=> " + fileReplacement.ResolvedPath); } private unsafe void AddReplacementsFromRenderModel(RenderModel* mdl, CharacterData cache, int inheritanceLevel = 0, string objectKind = "") @@ -116,7 +116,7 @@ public class CharacterDataFactory Stopwatch st = Stopwatch.StartNew(); 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); } _dalamudUtil.WaitWhileCharacterIsDrawing(_dalamudUtil.PlayerPointer); diff --git a/MareSynchronos/FileCacheDB/FileCacheContext.cs b/MareSynchronos/FileCacheDB/FileCacheContext.cs index 98f56f3..63fa39f 100644 --- a/MareSynchronos/FileCacheDB/FileCacheContext.cs +++ b/MareSynchronos/FileCacheDB/FileCacheContext.cs @@ -10,8 +10,26 @@ namespace MareSynchronos.FileCacheDB { 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(); } @@ -26,19 +44,7 @@ namespace MareSynchronos.FileCacheDB { if (!optionsBuilder.IsConfigured) { - string dbPath = Path.Combine(Plugin.PluginInterface.ConfigDirectory.FullName, "FileCacheDebug.db"); - 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); + optionsBuilder.UseSqlite("Data Source=" + DbPath); } } diff --git a/MareSynchronos/Managers/CachedPlayer.cs b/MareSynchronos/Managers/CachedPlayer.cs index 6210012..e0ea83a 100644 --- a/MareSynchronos/Managers/CachedPlayer.cs +++ b/MareSynchronos/Managers/CachedPlayer.cs @@ -178,12 +178,13 @@ public class CachedPlayer public void DisposePlayer() { - Logger.Debug("Disposing " + PlayerName + " (" + PlayerNameHash + ")"); if (_isDisposed) return; if (string.IsNullOrEmpty(PlayerName)) return; + Logger.Verbose("Disposing " + PlayerName + " (" + PlayerNameHash + ")"); + _isDisposed = true; try { - Logger.Debug("Restoring state for " + PlayerName); + Logger.Verbose("Restoring state for " + PlayerName); _dalamudUtil.FrameworkUpdate -= DalamudUtilOnFrameworkUpdate; _ipcManager.PenumbraRedrawEvent -= IpcManagerOnPenumbraRedrawEvent; _apiController.CharacterReceived -= ApiControllerOnCharacterReceived; @@ -191,7 +192,7 @@ public class CachedPlayer _downloadCancellationTokenSource?.Dispose(); _downloadCancellationTokenSource = null; _ipcManager.PenumbraRemoveTemporaryCollection(PlayerName); - if (PlayerCharacter != null) + if (PlayerCharacter != null && PlayerCharacter.IsValid()) { _ipcManager.GlamourerApplyOnlyCustomization(_originalGlamourerData, PlayerCharacter); _ipcManager.GlamourerApplyOnlyEquipment(_lastGlamourerData, PlayerCharacter); @@ -206,7 +207,6 @@ public class CachedPlayer PlayerName = string.Empty; PlayerCharacter = null; IsVisible = false; - _isDisposed = true; } } diff --git a/MareSynchronos/Managers/FileCacheManager.cs b/MareSynchronos/Managers/FileCacheManager.cs index ff4c5ce..159d498 100644 --- a/MareSynchronos/Managers/FileCacheManager.cs +++ b/MareSynchronos/Managers/FileCacheManager.cs @@ -25,22 +25,22 @@ namespace MareSynchronos.Managers private Task? _scanTask; public FileCacheManager(IpcManager ipcManager, Configuration pluginConfiguration) { - Logger.Debug("Creating " + nameof(FileCacheManager)); + Logger.Verbose("Creating " + nameof(FileCacheManager)); _ipcManager = ipcManager; _pluginConfiguration = pluginConfiguration; StartWatchersAndScan(); - _ipcManager.PenumbraInitialized += IpcManagerOnPenumbraInitialized; - _ipcManager.PenumbraDisposed += IpcManagerOnPenumbraDisposed; + _ipcManager.PenumbraInitialized += StartWatchersAndScan; + _ipcManager.PenumbraDisposed += StopWatchersAndScan; } public long CurrentFileProgress { get; private 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; } @@ -67,10 +67,10 @@ namespace MareSynchronos.Managers public void Dispose() { - Logger.Debug("Disposing " + nameof(FileCacheManager)); + Logger.Verbose("Disposing " + nameof(FileCacheManager)); - _ipcManager.PenumbraInitialized -= IpcManagerOnPenumbraInitialized; - _ipcManager.PenumbraDisposed -= IpcManagerOnPenumbraDisposed; + _ipcManager.PenumbraInitialized -= StartWatchersAndScan; + _ipcManager.PenumbraDisposed -= StopWatchersAndScan; _rescanTaskCancellationTokenSource?.Cancel(); _rescanTaskRunCancellationTokenSource?.Cancel(); _scanCancellationTokenSource?.Cancel(); @@ -121,16 +121,6 @@ namespace MareSynchronos.Managers Task.Run(RecalculateFileCacheSize); } - private void IpcManagerOnPenumbraDisposed(object? sender, EventArgs e) - { - StopWatchersAndScan(); - } - - private void IpcManagerOnPenumbraInitialized(object? sender, EventArgs e) - { - StartWatchersAndScan(); - } - private bool IsFileLocked(FileInfo file) { try @@ -217,6 +207,7 @@ namespace MareSynchronos.Managers private async Task StartFileScan(CancellationToken ct) { + TotalFiles = 1; _scanCancellationTokenSource = new CancellationTokenSource(); var penumbraDir = _ipcManager.PenumbraModDirectory()!; Logger.Debug("Getting files from " + penumbraDir + " and " + _pluginConfiguration.CacheFolder); @@ -237,7 +228,7 @@ namespace MareSynchronos.Managers var fileCachesToDelete = new ConcurrentBag(); var fileCachesToAdd = new ConcurrentBag(); - Logger.Debug("Getting file list from Database"); + Logger.Verbose("Getting file list from Database"); // scan files from database Parallel.ForEach(fileCaches, new ParallelOptions() { diff --git a/MareSynchronos/Managers/IpcManager.cs b/MareSynchronos/Managers/IpcManager.cs index c292667..4544595 100644 --- a/MareSynchronos/Managers/IpcManager.cs +++ b/MareSynchronos/Managers/IpcManager.cs @@ -7,6 +7,7 @@ using System.Linq; using Dalamud.Game.ClientState.Objects.Types; using Lumina.Excel.GeneratedSheets; using MareSynchronos.Utils; +using MareSynchronos.WebAPI; namespace MareSynchronos.Managers { @@ -33,7 +34,7 @@ namespace MareSynchronos.Managers _penumbraSetTemporaryMod; public IpcManager(DalamudPluginInterface pi) { - Logger.Debug("Creating " + nameof(IpcManager)); + Logger.Verbose("Creating " + nameof(IpcManager)); _penumbraInit = pi.GetIpcSubscriber("Penumbra.Initialized"); _penumbraDispose = pi.GetIpcSubscriber("Penumbra.Disposed"); @@ -69,12 +70,12 @@ namespace MareSynchronos.Managers if (Initialized) { - PenumbraInitialized?.Invoke(null, EventArgs.Empty); + PenumbraInitialized?.Invoke(); } } - public event EventHandler? PenumbraInitialized; - public event EventHandler? PenumbraDisposed; + public event VoidDelegate? PenumbraInitialized; + public event VoidDelegate? PenumbraDisposed; public event EventHandler? PenumbraRedrawEvent; public bool Initialized => CheckPenumbraApi(); @@ -104,32 +105,31 @@ namespace MareSynchronos.Managers public void Dispose() { - Logger.Debug("Disposing " + nameof(IpcManager)); + Logger.Verbose("Disposing " + nameof(IpcManager)); _penumbraDispose.Unsubscribe(PenumbraDispose); _penumbraInit.Unsubscribe(PenumbraInit); _penumbraObjectIsRedrawn.Unsubscribe(RedrawEvent); - Logger.Debug("IPC Manager disposed"); } public void GlamourerApplyAll(string customization, GameObject character) { if (!CheckGlamourerApi()) return; - Logger.Debug("Glamourer apply all to " + character); + Logger.Verbose("Glamourer apply all to " + character); _glamourerApplyAll!.InvokeAction(customization, character); } public void GlamourerApplyOnlyEquipment(string customization, GameObject character) { 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); } public void GlamourerApplyOnlyCustomization(string customization, GameObject character) { 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); } @@ -148,7 +148,7 @@ namespace MareSynchronos.Managers public string PenumbraCreateTemporaryCollection(string characterName) { 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); return ret.Item2; } @@ -174,7 +174,7 @@ namespace MareSynchronos.Managers public void PenumbraRemoveTemporaryCollection(string characterName) { if (!CheckPenumbraApi()) return; - Logger.Debug("Removing temp collection for " + characterName); + Logger.Verbose("Removing temp collection for " + characterName); _penumbraRemoveTemporaryCollection.InvokeFunc(characterName); } @@ -182,7 +182,7 @@ namespace MareSynchronos.Managers { if (!CheckPenumbraApi()) return null; var resolvedPath = _penumbraResolvePath!.InvokeFunc(path, characterName); - PluginLog.Verbose("Resolving " + path + Environment.NewLine + "=>" + string.Join(", ", resolvedPath)); + Logger.Verbose("Resolved " + path + "=>" + string.Join(", ", resolvedPath)); return resolvedPath; } @@ -190,7 +190,7 @@ namespace MareSynchronos.Managers { if (!CheckPenumbraApi()) return new[] { path }; 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; } @@ -198,7 +198,7 @@ namespace MareSynchronos.Managers { if (!CheckPenumbraApi()) return; - Logger.Debug("Assigning temp mods for " + collectionName); + Logger.Verbose("Assigning temp mods for " + collectionName); foreach (var mod in modPaths) { Logger.Verbose(mod.Key + " => " + mod.Value); @@ -213,13 +213,13 @@ namespace MareSynchronos.Managers private void PenumbraInit() { - PenumbraInitialized?.Invoke(null, EventArgs.Empty); + PenumbraInitialized?.Invoke(); _penumbraRedraw!.InvokeAction("self", 0); } private void PenumbraDispose() { - PenumbraDisposed?.Invoke(null, EventArgs.Empty); + PenumbraDisposed?.Invoke(); } } } diff --git a/MareSynchronos/Managers/OnlinePlayerManager.cs b/MareSynchronos/Managers/OnlinePlayerManager.cs index fbd6682..6b8c374 100644 --- a/MareSynchronos/Managers/OnlinePlayerManager.cs +++ b/MareSynchronos/Managers/OnlinePlayerManager.cs @@ -27,7 +27,7 @@ public class OnlinePlayerManager : IDisposable public OnlinePlayerManager(Framework framework, ApiController apiController, DalamudUtil dalamudUtil, IpcManager ipcManager, PlayerManager playerManager) { - Logger.Debug("Creating " + nameof(OnlinePlayerManager)); + Logger.Verbose("Creating " + nameof(OnlinePlayerManager)); _framework = framework; _apiController = apiController; @@ -74,7 +74,7 @@ public class OnlinePlayerManager : IDisposable PushCharacterData(OnlineVisiblePlayerHashes); } - private void ApiControllerOnConnected(object? sender, EventArgs e) + private void ApiControllerOnConnected() { var apiTask = _apiController.GetOnlineCharacters(); @@ -95,12 +95,12 @@ public class OnlinePlayerManager : IDisposable _framework.Update += FrameworkOnUpdate; } - private void IpcManagerOnPenumbraDisposed(object? sender, EventArgs e) + private void IpcManagerOnPenumbraDisposed() { _onlineCachedPlayers.ForEach(p => p.DisposePlayer()); } - private void ApiControllerOnDisconnected(object? sender, EventArgs e) + private void ApiControllerOnDisconnected() { RestoreAllCharacters(); _playerManager.PlayerHasChanged -= PlayerManagerOnPlayerHasChanged; @@ -110,12 +110,12 @@ public class OnlinePlayerManager : IDisposable { _onlineCachedPlayers.Clear(); _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() { - Logger.Debug("Disposing " + nameof(OnlinePlayerManager)); + Logger.Verbose("Disposing " + nameof(OnlinePlayerManager)); RestoreAllCharacters(); @@ -140,37 +140,28 @@ public class OnlinePlayerManager : IDisposable _onlineCachedPlayers.Clear(); } - public async Task UpdatePlayersFromService(Dictionary playerJobIds) + private void ApiControllerOnPairedClientOffline(string charHash) { - if (!playerJobIds.Any()) return; - Logger.Debug("Getting data for new players: " + string.Join(Environment.NewLine, playerJobIds)); - await _apiController.GetCharacterData(playerJobIds); + Logger.Debug("Player offline: " + charHash); + RemovePlayer(charHash); } - private void ApiControllerOnPairedClientOffline(object? sender, EventArgs e) + private void ApiControllerOnPairedClientOnline(string charHash) { - Logger.Debug("Player offline: " + sender!); - RemovePlayer((string)sender!); - } - - private void ApiControllerOnPairedClientOnline(object? sender, EventArgs e) - { - Logger.Debug("Player online: " + sender!); - AddPlayer((string)sender!); + Logger.Debug("Player online: " + charHash); + AddPlayer(charHash); return; } - private void ApiControllerOnPairedWithOther(object? sender, EventArgs e) + private void ApiControllerOnPairedWithOther(string charHash) { - var characterHash = (string?)sender; - if (string.IsNullOrEmpty(characterHash)) return; - Logger.Debug("Pairing with " + characterHash); - AddPlayer(characterHash); + if (string.IsNullOrEmpty(charHash)) return; + Logger.Debug("Pairing with " + charHash); + AddPlayer(charHash); } - private void ApiControllerOnUnpairedFromOther(object? sender, EventArgs e) + private void ApiControllerOnUnpairedFromOther(string? characterHash) { - var characterHash = (string?)sender; if (string.IsNullOrEmpty(characterHash)) return; Logger.Debug("Unpairing from " + characterHash); RemovePlayer(characterHash); @@ -228,8 +219,8 @@ public class OnlinePlayerManager : IDisposable { Task.Run(async () => { - Logger.Verbose(JsonConvert.SerializeObject(_playerManager.LastSentCharacterData!.ToCharacterCacheDto(), Formatting.Indented)); - await _apiController.PushCharacterData(_playerManager.LastSentCharacterData.ToCharacterCacheDto(), + Logger.Verbose(JsonConvert.SerializeObject(_playerManager.LastSentCharacterData, Formatting.Indented)); + await _apiController.PushCharacterData(_playerManager.LastSentCharacterData, visiblePlayers); }); } diff --git a/MareSynchronos/Managers/PlayerManager.cs b/MareSynchronos/Managers/PlayerManager.cs index 41aab69..351c794 100644 --- a/MareSynchronos/Managers/PlayerManager.cs +++ b/MareSynchronos/Managers/PlayerManager.cs @@ -22,7 +22,7 @@ namespace MareSynchronos.Managers private readonly IpcManager _ipcManager; public event PlayerHasChanged? PlayerHasChanged; public bool SendingData { get; private set; } - public CharacterData? LastSentCharacterData { get; private set; } + public CharacterCacheDto? LastSentCharacterData { get; private set; } private CancellationTokenSource? _playerChangedCts; private DateTime _lastPlayerObjectCheck; @@ -31,28 +31,28 @@ namespace MareSynchronos.Managers public PlayerManager(ApiController apiController, IpcManager ipcManager, CharacterDataFactory characterDataFactory, DalamudUtil dalamudUtil) { - Logger.Debug("Creating " + nameof(PlayerManager)); + Logger.Verbose("Creating " + nameof(PlayerManager)); _apiController = apiController; _ipcManager = ipcManager; _characterDataFactory = characterDataFactory; _dalamudUtil = dalamudUtil; - _apiController.Connected += ApiController_Connected; + _apiController.Connected += ApiControllerOnConnected; _apiController.Disconnected += ApiController_Disconnected; Logger.Debug("Watching Player, ApiController is Connected: " + _apiController.IsConnected); if (_apiController.IsConnected) { - ApiController_Connected(null, EventArgs.Empty); + ApiControllerOnConnected(); } } public void Dispose() { - Logger.Debug("Disposing " + nameof(PlayerManager)); + Logger.Verbose("Disposing " + nameof(PlayerManager)); - _apiController.Connected -= ApiController_Connected; + _apiController.Connected -= ApiControllerOnConnected; _apiController.Disconnected -= ApiController_Disconnected; _ipcManager.PenumbraRedrawEvent -= IpcManager_PenumbraRedrawEvent; @@ -73,7 +73,7 @@ namespace MareSynchronos.Managers _lastPlayerObjectCheck = DateTime.Now; } - private void ApiController_Connected(object? sender, EventArgs args) + private void ApiControllerOnConnected() { Logger.Debug("ApiController Connected"); @@ -84,17 +84,19 @@ namespace MareSynchronos.Managers PlayerChanged(); } - private void ApiController_Disconnected(object? sender, EventArgs args) + private void ApiController_Disconnected() { Logger.Debug(nameof(ApiController_Disconnected)); _ipcManager.PenumbraRedrawEvent -= IpcManager_PenumbraRedrawEvent; _dalamudUtil.FrameworkUpdate -= DalamudUtilOnFrameworkUpdate; + LastSentCharacterData = null; } - private async Task CreateFullCharacterCache(CancellationToken token) + private async Task CreateFullCharacterCache(CancellationToken token) { var cache = _characterDataFactory.BuildCharacterData(); + CharacterCacheDto? cacheDto = null; await Task.Run(async () => { @@ -105,12 +107,13 @@ namespace MareSynchronos.Managers 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); - return cache; + return cacheDto; } private void IpcManager_PenumbraRedrawEvent(object? objectTableIndex, EventArgs e) @@ -160,32 +163,21 @@ namespace MareSynchronos.Managers if (attempts == 10 || token.IsCancellationRequested) return; - Stopwatch st = Stopwatch.StartNew(); _dalamudUtil.WaitWhileSelfIsDrawing(token); - var characterCache = await CreateFullCharacterCache(token); + var characterCache = (await CreateFullCharacterCache(token))!; if (token.IsCancellationRequested) return; - var cacheDto = characterCache.ToCharacterCacheDto(); - st.Stop(); - - if (token.IsCancellationRequested) - { - return; - } - - Logger.Debug("Elapsed time PlayerChangedTask: " + st.Elapsed); - if (cacheDto.Hash == (LastSentCharacterData?.CacheHash ?? "-")) + if (characterCache.Hash == (LastSentCharacterData?.Hash ?? "-")) { Logger.Debug("Not sending data, already sent"); return; } LastSentCharacterData = characterCache; - PlayerHasChanged?.Invoke(cacheDto); + PlayerHasChanged?.Invoke(characterCache); SendingData = false; - }, token); } diff --git a/MareSynchronos/MareSynchronos.csproj b/MareSynchronos/MareSynchronos.csproj index d723ece..b5d50e4 100644 --- a/MareSynchronos/MareSynchronos.csproj +++ b/MareSynchronos/MareSynchronos.csproj @@ -3,7 +3,7 @@ - 0.0.0.1 + 0.0.2.0 https://github.com/Penumbra-Sync/client @@ -71,10 +71,13 @@ Never + + PreserveNewest + - + diff --git a/MareSynchronos/MareSynchronos.json b/MareSynchronos/MareSynchronos.json index 717e086..9875750 100644 --- a/MareSynchronos/MareSynchronos.json +++ b/MareSynchronos/MareSynchronos.json @@ -2,13 +2,11 @@ "Author": "darkarchon", "Name": "Mare Synchronos", "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", "ApplicableVersion": "any", "Tags": [ - "sample", - "plugin", - "goats" + "customization" ], "IconUrl": "https://raw.githubusercontent.com/Penumbra-Sync/client/main/MareSynchronos/images/logo.png", "RepoUrl": "https://github.com/Penumbra-Sync/client" diff --git a/MareSynchronos/Models/CharacterData.cs b/MareSynchronos/Models/CharacterData.cs index 4e404d4..541bba7 100644 --- a/MareSynchronos/Models/CharacterData.cs +++ b/MareSynchronos/Models/CharacterData.cs @@ -9,20 +9,6 @@ namespace MareSynchronos.Models [JsonObject(MemberSerialization.OptIn)] public class CharacterData { - [JsonProperty] - public List 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 FileReplacements { get; set; } = new(); [JsonProperty] @@ -54,9 +40,15 @@ namespace MareSynchronos.Models { 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, - Hash = CacheHash, JobId = JobId, ManipulationData = ManipulationString }; diff --git a/MareSynchronos/Models/FileReplacement.cs b/MareSynchronos/Models/FileReplacement.cs index 06996b2..c9eb7ab 100644 --- a/MareSynchronos/Models/FileReplacement.cs +++ b/MareSynchronos/Models/FileReplacement.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using Newtonsoft.Json; using MareSynchronos.FileCacheDB; using System.IO; using MareSynchronos.API; @@ -12,29 +11,23 @@ using MareSynchronos.Utils; namespace MareSynchronos.Models { - [JsonObject(MemberSerialization.OptIn)] public class FileReplacement { private readonly string _penumbraDirectory; - private Task? _computationTask = null; - 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 GamePaths { get; set; } = new(); public bool HasFileReplacement => GamePaths.Count >= 1 && GamePaths.Any(p => p != ResolvedPath); - [JsonProperty] public string Hash { get; set; } = string.Empty; - [JsonProperty] public string ResolvedPath { get; set; } = string.Empty; public void SetResolvedPath(string path) @@ -42,7 +35,7 @@ namespace MareSynchronos.Models ResolvedPath = path.ToLower().Replace('/', '\\').Replace(_penumbraDirectory, "").Replace('\\', '/'); if (!HasFileReplacement) return; - _computationTask = Task.Run(() => + _ = Task.Run(() => { FileCache? fileCache; using (FileCacheContext db = new()) diff --git a/MareSynchronos/Plugin.cs b/MareSynchronos/Plugin.cs index 27da962..d88c824 100644 --- a/MareSynchronos/Plugin.cs +++ b/MareSynchronos/Plugin.cs @@ -11,6 +11,7 @@ using Dalamud.Interface.ImGuiFileDialog; using MareSynchronos.Managers; using MareSynchronos.WebAPI; using Dalamud.Interface.Windowing; +using Dalamud.Logging; using MareSynchronos.UI; using MareSynchronos.Utils; @@ -81,7 +82,7 @@ namespace MareSynchronos _dalamudUtil.LogIn += DalamudUtilOnLogIn; _dalamudUtil.LogOut += DalamudUtilOnLogOut; - _apiController.ChangingServers += ApiControllerOnChangingServers; + _apiController.RegisterFinalized += ApiControllerOnRegisterFinalized; if (_dalamudUtil.IsLoggedIn) { @@ -89,7 +90,7 @@ namespace MareSynchronos } } - private void ApiControllerOnChangingServers(object? sender, EventArgs e) + private void ApiControllerOnRegisterFinalized() { _mainUi.IsOpen = false; _introUi.IsOpen = true; @@ -98,8 +99,8 @@ namespace MareSynchronos public string Name => "Mare Synchronos"; public void Dispose() { - Logger.Debug("Disposing " + Name); - _apiController.ChangingServers -= ApiControllerOnChangingServers; + Logger.Verbose("Disposing " + Name); + _apiController.RegisterFinalized -= ApiControllerOnRegisterFinalized; _apiController?.Dispose(); _commandManager.RemoveHandler(CommandName); @@ -114,6 +115,7 @@ namespace MareSynchronos _ipcManager?.Dispose(); _playerManager?.Dispose(); _characterCacheManager?.Dispose(); + PluginLog.Information("Shut down"); } diff --git a/MareSynchronos/UI/DownloadUi.cs b/MareSynchronos/UI/DownloadUi.cs index 18276da..cb684c7 100644 --- a/MareSynchronos/UI/DownloadUi.cs +++ b/MareSynchronos/UI/DownloadUi.cs @@ -17,13 +17,13 @@ public class DownloadUi : Window, IDisposable public void Dispose() { - Logger.Debug("Disposing " + nameof(DownloadUi)); + Logger.Verbose("Disposing " + nameof(DownloadUi)); _windowSystem.RemoveWindow(this); } 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; _pluginConfiguration = pluginConfiguration; _apiController = apiController; diff --git a/MareSynchronos/UI/IntroUI.cs b/MareSynchronos/UI/IntroUI.cs index 140e5e4..dd95e92 100644 --- a/MareSynchronos/UI/IntroUI.cs +++ b/MareSynchronos/UI/IntroUI.cs @@ -20,7 +20,7 @@ namespace MareSynchronos.UI public void Dispose() { - Logger.Debug("Disposing " + nameof(IntroUi)); + Logger.Verbose("Disposing " + nameof(IntroUi)); _windowSystem.RemoveWindow(this); } @@ -28,7 +28,7 @@ namespace MareSynchronos.UI public IntroUi(WindowSystem windowSystem, UiShared uiShared, Configuration pluginConfiguration, FileCacheManager fileCacheManager) : base("Mare Synchronos Setup") { - Logger.Debug("Creating " + nameof(IntroUi)); + Logger.Verbose("Creating " + nameof(IntroUi)); _uiShared = uiShared; _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."); 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.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. If you want to use this plugin you will have to move your mods to Penumbra."); - ImGui.PopStyleColor(); + UiShared.ColorTextWrapped("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. " + + "If you want to use this plugin you will have to move your mods to Penumbra.", ImGuiColors.DalamudYellow); if (!_uiShared.DrawOtherPluginState()) return; ImGui.Separator(); 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. " + "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."); - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); - 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. " + + 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. " + "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."); - ImGui.PopStyleColor(); - 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(); + "Locally cached mod files will have arbitrary file names to discourage attempts at replicating the original mod.", ImGuiColors.DalamudRed); + 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); 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. " + "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."); - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); - 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'"); - ImGui.PopStyleColor(); + UiShared.ColorTextWrapped("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); ImGui.Separator(); if (ImGui.Button("I agree##toSetup")) diff --git a/MareSynchronos/UI/MainUi.cs b/MareSynchronos/UI/MainUi.cs index ae1333b..6dbf5b7 100644 --- a/MareSynchronos/UI/MainUi.cs +++ b/MareSynchronos/UI/MainUi.cs @@ -27,7 +27,7 @@ namespace MareSynchronos.UI public MainUi(WindowSystem windowSystem, 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() { @@ -44,7 +44,7 @@ namespace MareSynchronos.UI public void Dispose() { - Logger.Debug("Disposing " + nameof(MainUi)); + Logger.Verbose("Disposing " + nameof(MainUi)); _windowSystem.RemoveWindow(this); } @@ -66,11 +66,12 @@ namespace MareSynchronos.UI { _uiShared.PrintServerState(); ImGui.Separator(); - ImGui.SetWindowFontScale(1.2f); - ImGui.Text("Your UID"); - ImGui.SameLine(); - if (_apiController.IsConnected) + + if (_apiController.ServerState is ServerState.Connected) { + ImGui.SetWindowFontScale(1.2f); + ImGui.Text("Your UID"); + ImGui.SameLine(); ImGui.TextColored(ImGuiColors.ParsedGreen, _apiController.UID); ImGui.SameLine(); ImGui.SetWindowFontScale(1.0f); @@ -83,33 +84,44 @@ namespace MareSynchronos.UI } else { - var error = _configuration.FullPause ? "Disconnected" - : !_apiController.ServerAlive - ? "Service unavailable" - : !_apiController.ServerSupportsThisClient - ? "Service version mismatch" - : "Unauthorized"; - ImGui.TextColored(ImGuiColors.DalamudRed, $"No UID ({error})"); + string errorMsg = _apiController.ServerState switch + { + ServerState.Disconnected => "Disconnected", + ServerState.Unauthorized => "Unauthorized", + ServerState.VersionMisMatch => "Service version mismatch", + ServerState.Offline => "Service unavailable" + }; + ImGui.SetWindowFontScale(1.2f); + ImGui.TextColored(ImGuiColors.DalamudRed, $"No UID ({errorMsg})"); ImGui.SetWindowFontScale(1.0f); - if (_apiController.ServerAlive && !_configuration.FullPause && _apiController.ServerSupportsThisClient) + switch (_apiController.ServerState) { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); - UiShared.TextWrapped("Your account is not present on the service anymore or you are banned."); - ImGui.PopStyleColor(); - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); - 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."); - ImGui.PopStyleColor(); - if (ImGui.Button("Reset Secret Key")) - { - _configuration.ClientSecret.Remove(_configuration.ApiUri); - _configuration.Save(); - SwitchFromMainUiToIntro?.Invoke(); - } - } else if (!_apiController.ServerSupportsThisClient) - { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); - 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."); - ImGui.PopStyleColor(); + case ServerState.Disconnected: + UiShared.ColorTextWrapped("You are currently disconnected from the Mare Synchronos service.", ImGuiColors.DalamudRed); + break; + case ServerState.Unauthorized: + UiShared.ColorTextWrapped("Your account is not present on the service anymore or you are banned.", ImGuiColors.DalamudRed); + UiShared.ColorTextWrapped("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.", ImGuiColors.DalamudYellow); + if (ImGui.Button("Reset Secret Key")) + { + _configuration.ClientSecret.Remove(_configuration.ApiUri); + _configuration.Save(); + SwitchFromMainUiToIntro?.Invoke(); + } + break; + case ServerState.Offline: + 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) { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); - UiShared.TextWrapped("Note: to change servers you need to disconnect from your current Mare Synchronos server."); - ImGui.PopStyleColor(); + UiShared.ColorTextWrapped("Note: to change servers you need to disconnect from your current Mare Synchronos server.", ImGuiColors.DalamudYellow); } var marePaused = _configuration.FullPause; @@ -485,18 +495,14 @@ namespace MareSynchronos.UI } else { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); - ImGui.TextUnformatted("You cannot reconnect without a valid account on the service."); - ImGui.PopStyleColor(); + UiShared.ColorText("You cannot reconnect without a valid account on the service.", ImGuiColors.DalamudYellow); } - if (marePaused) { _uiShared.DrawServiceSelection(() => SwitchFromMainUiToIntro?.Invoke()); } - ImGui.TreePop(); } } @@ -506,11 +512,10 @@ namespace MareSynchronos.UI if (ImGui.TreeNode( $"Forbidden Transfers")) { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudGrey); - UiShared.TextWrapped("Files that you attempted to upload or download that were forbidden to be transferred by their creators will appear here. " + + UiShared.ColorTextWrapped("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. " + - "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(); + "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.", + ImGuiColors.DalamudGrey); if (ImGui.BeginTable("TransfersTable", 2, ImGuiTableFlags.SizingStretchProp)) { @@ -579,7 +584,7 @@ namespace MareSynchronos.UI ImGui.TableSetupColumn("Uploaded"); ImGui.TableSetupColumn("Size"); ImGui.TableHeadersRow(); - foreach (var transfer in _apiController.CurrentUploads) + foreach (var transfer in _apiController.CurrentUploads.ToArray()) { var color = UiShared.UploadColor((transfer.Transferred, transfer.Total)); ImGui.PushStyleColor(ImGuiCol.Text, color); @@ -603,7 +608,7 @@ namespace MareSynchronos.UI ImGui.TableSetupColumn("Downloaded"); ImGui.TableSetupColumn("Size"); ImGui.TableHeadersRow(); - foreach (var transfer in _apiController.CurrentDownloads) + foreach (var transfer in _apiController.CurrentDownloads.ToArray()) { var color = UiShared.UploadColor((transfer.Transferred, transfer.Total)); ImGui.PushStyleColor(ImGuiCol.Text, color); diff --git a/MareSynchronos/UI/UIShared.cs b/MareSynchronos/UI/UIShared.cs index 19a82e7..8c0d08e 100644 --- a/MareSynchronos/UI/UIShared.cs +++ b/MareSynchronos/UI/UIShared.cs @@ -34,7 +34,7 @@ namespace MareSynchronos.UI _fileDialogManager = fileDialogManager; _pluginConfiguration = pluginConfiguration; _dalamudUtil = dalamudUtil; - isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder); + _isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder); } public bool DrawOtherPluginState() @@ -85,7 +85,7 @@ namespace MareSynchronos.UI var serverName = _apiController.ServerDictionary.ContainsKey(_pluginConfiguration.ApiUri) ? _apiController.ServerDictionary[_pluginConfiguration.ApiUri] : _pluginConfiguration.ApiUri; - ImGui.Text("Service " + serverName + ":"); + ImGui.TextUnformatted("Service " + serverName + ":"); ImGui.SameLine(); var color = _apiController.ServerAlive ? ImGuiColors.ParsedGreen : ImGuiColors.DalamudRed; 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) { ImGui.PushTextWrapPos(0); @@ -238,9 +252,7 @@ namespace MareSynchronos.UI } else { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudYellow); - TextWrapped("You already have an account on this server."); - ImGui.PopStyleColor(); + ColorTextWrapped("You already have an account on this server.", ImGuiColors.DalamudYellow); ImGui.SameLine(); if (ImGui.Button("Connect##connectToService")) { @@ -301,7 +313,7 @@ namespace MareSynchronos.UI _pluginConfiguration.CacheFolder = cacheDirectory; if (!string.IsNullOrEmpty(_pluginConfiguration.CacheFolder) && Directory.Exists(_pluginConfiguration.CacheFolder) - && (isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder))) + && (_isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder))) { _pluginConfiguration.Save(); _fileCacheManager.StartWatchers(); @@ -318,8 +330,8 @@ namespace MareSynchronos.UI if (!success) return; _pluginConfiguration.CacheFolder = path; - isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder); - if (isDirectoryWritable) + _isDirectoryWritable = IsDirectoryWritable(_pluginConfiguration.CacheFolder); + if (_isDirectoryWritable) { _pluginConfiguration.Save(); _fileCacheManager.StartWatchers(); @@ -328,15 +340,13 @@ namespace MareSynchronos.UI } ImGui.PopFont(); - if (!Directory.Exists(cacheDirectory) || !isDirectoryWritable) + if (!Directory.Exists(cacheDirectory) || !_isDirectoryWritable) { - ImGui.PushStyleColor(ImGuiCol.Text, ImGuiColors.DalamudRed); - TextWrapped("The folder you selected does not exist or cannot be written to. Please provide a valid path."); - ImGui.PopStyleColor(); + ColorTextWrapped("The folder you selected does not exist or cannot be written to. Please provide a valid path.", ImGuiColors.DalamudRed); } } - private bool isDirectoryWritable = false; + private bool _isDirectoryWritable = false; public bool IsDirectoryWritable(string dirPath, bool throwIfFails = false) { diff --git a/MareSynchronos/WebAPI/ApIController.Functions.Users.cs b/MareSynchronos/WebAPI/ApIController.Functions.Users.cs index c70c8e5..4976003 100644 --- a/MareSynchronos/WebAPI/ApIController.Functions.Users.cs +++ b/MareSynchronos/WebAPI/ApIController.Functions.Users.cs @@ -17,12 +17,6 @@ namespace MareSynchronos.WebAPI await CreateConnections(); } - public async Task GetCharacterData(Dictionary hashedCharacterNames) - { - await _userHub!.InvokeAsync("GetCharacterData", - hashedCharacterNames); - } - public async Task Register() { if (!ServerAlive) return; @@ -30,7 +24,7 @@ namespace MareSynchronos.WebAPI var response = await _userHub!.InvokeAsync("Register"); _pluginConfiguration.ClientSecret[ApiUri] = response; _pluginConfiguration.Save(); - ChangingServers?.Invoke(null, EventArgs.Empty); + RegisterFinalized?.Invoke(); await CreateConnections(); } diff --git a/MareSynchronos/WebAPI/ApiController.Connectivity.cs b/MareSynchronos/WebAPI/ApiController.Connectivity.cs index df4fac2..0021ba7 100644 --- a/MareSynchronos/WebAPI/ApiController.Connectivity.cs +++ b/MareSynchronos/WebAPI/ApiController.Connectivity.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.Http; @@ -13,21 +12,32 @@ using Microsoft.AspNetCore.SignalR.Client; 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 { #if DEBUG - public const string MainServer = "darkarchons Debug Server (Dev Server (CH))"; - public const string MainServiceUri = "wss://darkarchon.internet-box.ch:5000"; - public readonly int[] SupportedServerVersions = { 1 }; + public const string MainServer = "Lunae Crescere Incipientis (Central Server EU)"; + public const string MainServiceUri = "wss://v2202207178628194299.powersrv.de:6871"; #else 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 + public readonly int[] SupportedServerVersions = { 1 }; private readonly Configuration _pluginConfiguration; private readonly DalamudUtil _dalamudUtil; - private CancellationTokenSource _cts; + private CancellationTokenSource _connectionCancellationTokenSource; private HubConnection? _fileHub; @@ -45,11 +55,11 @@ namespace MareSynchronos.WebAPI public ApiController(Configuration pluginConfiguration, DalamudUtil dalamudUtil) { - Logger.Debug("Creating " + nameof(ApiController)); + Verbose.Debug("Creating " + nameof(ApiController)); _pluginConfiguration = pluginConfiguration; _dalamudUtil = dalamudUtil; - _cts = new CancellationTokenSource(); + _connectionCancellationTokenSource = new CancellationTokenSource(); _dalamudUtil.LogIn += DalamudUtilOnLogIn; _dalamudUtil.LogOut += DalamudUtilOnLogOut; @@ -61,7 +71,7 @@ namespace MareSynchronos.WebAPI private void DalamudUtilOnLogOut() { - Task.Run(async () => await StopAllConnections(_cts.Token)); + Task.Run(async () => await StopAllConnections(_connectionCancellationTokenSource.Token)); } private void DalamudUtilOnLogIn() @@ -70,21 +80,21 @@ namespace MareSynchronos.WebAPI } - public event EventHandler? ChangingServers; - public event EventHandler? 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 CurrentDownloads { get; } = new(); @@ -96,7 +106,7 @@ namespace MareSynchronos.WebAPI public List AdminForbiddenFiles { get; private set; } = new(); - public bool IsConnected => !string.IsNullOrEmpty(UID) && ServerSupportsThisClient; + public bool IsConnected => ServerState == ServerState.Connected; public bool IsDownloading => CurrentDownloads.Count > 0; @@ -104,33 +114,51 @@ namespace MareSynchronos.WebAPI public List 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 => (_heartbeatHub?.State ?? HubConnectionState.Disconnected) == HubConnectionState.Connected; - public bool ServerSupportsThisClient => SupportedServerVersions.Contains(_connectionDto?.ServerVersion ?? 0); - - public Dictionary ServerDictionary => new Dictionary() { { MainServiceUri, MainServer } } + public Dictionary ServerDictionary => new Dictionary() + { { MainServiceUri, MainServer } } .Concat(_pluginConfiguration.CustomServerList) .ToDictionary(k => k.Key, k => k.Value); public string UID => _connectionDto?.UID ?? string.Empty; - private string ApiUri => _pluginConfiguration.ApiUri; 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() { - await StopAllConnections(_cts.Token); + Logger.Verbose("Recreating Connection"); - _cts = new CancellationTokenSource(); - var token = _cts.Token; + await StopAllConnections(_connectionCancellationTokenSource.Token); + + _connectionCancellationTokenSource.Cancel(); + _connectionCancellationTokenSource = new CancellationTokenSource(); + var token = _connectionCancellationTokenSource.Token; while (!ServerAlive && !token.IsCancellationRequested) { - await StopAllConnections(token); - try { if (_dalamudUtil.PlayerCharacter == null) throw new ArgumentException("Player not initialized"); @@ -147,7 +175,7 @@ namespace MareSynchronos.WebAPI OnlineUsers = await _userHub.InvokeAsync("GetOnlineUsers", token); _userHub.On("UsersOnline", (count) => OnlineUsers = count); - + if (_pluginConfiguration.FullPause) { _connectionDto = null; @@ -155,16 +183,15 @@ namespace MareSynchronos.WebAPI } _connectionDto = await _heartbeatHub.InvokeAsync("Heartbeat", token); - if (!string.IsNullOrEmpty(UID) && !token.IsCancellationRequested - && ServerSupportsThisClient) // user is authorized && server is legit + if (ServerState is ServerState.Connected) // user is authorized && server is legit { Logger.Debug("Initializing data"); _userHub.On("UpdateClientPairs", UpdateLocalClientPairsCallback); _userHub.On("ReceiveCharacterData", ReceiveCharacterDataCallback); _userHub.On("RemoveOnlinePairedPlayer", - (s) => PairedClientOffline?.Invoke(s, EventArgs.Empty)); + (s) => PairedClientOffline?.Invoke(s)); _userHub.On("AddOnlinePairedPlayer", - (s) => PairedClientOnline?.Invoke(s, EventArgs.Empty)); + (s) => PairedClientOnline?.Invoke(s)); _adminHub.On("ForcedReconnect", UserForcedReconnectCallback); PairedClients = await _userHub!.InvokeAsync>("GetPairedClients", token); @@ -183,7 +210,7 @@ namespace MareSynchronos.WebAPI _adminHub.On("DeleteForbiddenFile", DeleteForbiddenFileCallback); } - Connected?.Invoke(this, EventArgs.Empty); + Connected?.Invoke(); } } catch (Exception ex) @@ -191,6 +218,7 @@ namespace MareSynchronos.WebAPI Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace ?? string.Empty); Logger.Debug("Failed to establish connection, retrying"); + await StopAllConnections(token); await Task.Delay(TimeSpan.FromSeconds(5), token); } } @@ -198,12 +226,12 @@ namespace MareSynchronos.WebAPI public void Dispose() { - Logger.Debug("Disposing " + nameof(ApiController)); + Logger.Verbose("Disposing " + nameof(ApiController)); _dalamudUtil.LogIn -= DalamudUtilOnLogIn; _dalamudUtil.LogOut -= DalamudUtilOnLogOut; - Task.Run(async () => await StopAllConnections(_cts.Token)); + Task.Run(async () => await StopAllConnections(_connectionCancellationTokenSource.Token)); } private HubConnection BuildHubConnection(string hubName) @@ -235,7 +263,7 @@ namespace MareSynchronos.WebAPI CurrentDownloads.Clear(); _uploadCancellationTokenSource?.Cancel(); Logger.Debug("Connection closed"); - Disconnected?.Invoke(null, EventArgs.Empty); + Disconnected?.Invoke(); return Task.CompletedTask; } @@ -244,7 +272,7 @@ namespace MareSynchronos.WebAPI Logger.Debug("Connection restored"); OnlineUsers = _userHub!.InvokeAsync("GetOnlineUsers").Result; _connectionDto = _heartbeatHub!.InvokeAsync("Heartbeat").Result; - Connected?.Invoke(this, EventArgs.Empty); + Connected?.Invoke(); return Task.CompletedTask; } @@ -254,12 +282,13 @@ namespace MareSynchronos.WebAPI CurrentDownloads.Clear(); _uploadCancellationTokenSource?.Cancel(); Logger.Debug("Connection closed... Reconnecting"); - Disconnected?.Invoke(null, EventArgs.Empty); + Disconnected?.Invoke(); return Task.CompletedTask; } private async Task StopAllConnections(CancellationToken token) { + Logger.Verbose("Stopping all connections"); if (_heartbeatHub is not null) { await _heartbeatHub.StopAsync(token); diff --git a/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs b/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs index 4ad9256..be7e59d 100644 --- a/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs +++ b/MareSynchronos/WebAPI/ApiController.Functions.Callbacks.cs @@ -20,7 +20,7 @@ namespace MareSynchronos.WebAPI if (dto.IsRemoved) { PairedClients.RemoveAll(p => p.OtherUID == dto.OtherUID); - UnpairedFromOther?.Invoke(characterIdentifier, EventArgs.Empty); + UnpairedFromOther?.Invoke(characterIdentifier); return; } if (entry == null) @@ -32,7 +32,7 @@ namespace MareSynchronos.WebAPI if ((entry.IsPausedFromOthers != dto.IsPausedFromOthers || entry.IsSynced != dto.IsSynced || entry.IsPaused != dto.IsPaused) && !dto.IsPaused && dto.IsSynced && !dto.IsPausedFromOthers) { - PairedWithOther?.Invoke(characterIdentifier, EventArgs.Empty); + PairedWithOther?.Invoke(characterIdentifier); } entry.IsPaused = dto.IsPaused; @@ -41,7 +41,7 @@ namespace MareSynchronos.WebAPI if (dto.IsPaused || dto.IsPausedFromOthers || !dto.IsSynced) { - UnpairedFromOther?.Invoke(characterIdentifier, EventArgs.Empty); + UnpairedFromOther?.Invoke(characterIdentifier); } } diff --git a/MareSynchronos/images/logo.png b/MareSynchronos/images/icon.png similarity index 100% rename from MareSynchronos/images/logo.png rename to MareSynchronos/images/icon.png