DI: Add Chat instead of using ChatExtensions

This commit is contained in:
Liza 2023-02-17 15:51:45 +01:00
parent 8b6dd52b54
commit 870f29f0c6
12 changed files with 74 additions and 54 deletions

View File

@ -19,7 +19,7 @@ namespace Pal.Client.Commands
{
private readonly IPalacePalConfiguration _configuration;
private readonly CommandManager _commandManager;
private readonly ChatGui _chatGui;
private readonly Chat _chat;
private readonly StatisticsService _statisticsService;
private readonly ConfigWindow _configWindow;
private readonly TerritoryState _territoryState;
@ -29,7 +29,7 @@ namespace Pal.Client.Commands
public PalCommand(
IPalacePalConfiguration configuration,
CommandManager commandManager,
ChatGui chatGui,
Chat chat,
StatisticsService statisticsService,
ConfigWindow configWindow,
TerritoryState territoryState,
@ -38,7 +38,7 @@ namespace Pal.Client.Commands
{
_configuration = configuration;
_commandManager = commandManager;
_chatGui = chatGui;
_chat = chat;
_statisticsService = statisticsService;
_configWindow = configWindow;
_territoryState = territoryState;
@ -60,7 +60,7 @@ namespace Pal.Client.Commands
{
if (_configuration.FirstUse)
{
_chatGui.PalError(Localization.Error_FirstTimeSetupRequired);
_chat.Error(Localization.Error_FirstTimeSetupRequired);
return;
}
@ -82,7 +82,7 @@ namespace Pal.Client.Commands
#if DEBUG
case "update-saves":
LocalState.UpdateAll();
_chatGui.PalMessage(Localization.Command_pal_updatesaves);
_chat.Message(Localization.Command_pal_updatesaves);
break;
#endif
@ -104,14 +104,14 @@ namespace Pal.Client.Commands
break;
default:
_chatGui.PalError(string.Format(Localization.Command_pal_UnknownSubcommand, arguments,
_chat.Error(string.Format(Localization.Command_pal_UnknownSubcommand, arguments,
command));
break;
}
}
catch (Exception e)
{
_chatGui.PalError(e.ToString());
_chat.Error(e.ToString());
}
}
@ -124,7 +124,7 @@ namespace Pal.Client.Commands
var playerPosition = _clientState.LocalPlayer?.Position;
if (playerPosition == null)
return;
_chatGui.PalMessage($"{playerPosition}");
_chat.Message($"{playerPosition}");
var nearbyMarkers = state.Markers
.Where(m => predicate(m))
@ -134,7 +134,7 @@ namespace Pal.Client.Commands
.Take(5)
.ToList();
foreach (var nearbyMarker in nearbyMarkers)
_chatGui.Print(
_chat.UnformattedMessage(
$"{nearbyMarker.distance:F2} - {nearbyMarker.m.Type} {nearbyMarker.m.NetworkId?.ToPartialId(length: 8)} - {nearbyMarker.m.Position}");
}
}

View File

@ -3,13 +3,20 @@ using Dalamud.Game.Text;
using Dalamud.Game.Text.SeStringHandling;
using Pal.Client.Properties;
namespace Pal.Client.Extensions
namespace Pal.Client.DependencyInjection
{
public static class ChatExtensions
internal sealed class Chat
{
public static void PalError(this ChatGui chat, string e)
private readonly ChatGui _chatGui;
public Chat(ChatGui chatGui)
{
chat.PrintChat(new XivChatEntry
_chatGui = chatGui;
}
public void Error(string e)
{
_chatGui.PrintChat(new XivChatEntry
{
Message = new SeStringBuilder()
.AddUiForeground($"[{Localization.Palace_Pal}] ", 16)
@ -18,11 +25,14 @@ namespace Pal.Client.Extensions
});
}
public static void PalMessage(this ChatGui chat, string message)
public void Message(string message)
{
chat.Print(new SeStringBuilder()
_chatGui.Print(new SeStringBuilder()
.AddUiForeground($"[{Localization.Palace_Pal}] ", 57)
.AddText(message).Build());
}
public void UnformattedMessage(string message)
=> _chatGui.Print(message);
}
}

View File

@ -91,7 +91,7 @@ namespace Pal.Client.DependencyInjection
return _dataManager.GetExcelSheet<LogMessage>()?.GetRow(id)?.Text?.ToString() ?? "Unknown";
}
private class LocalizedChatMessages
private sealed class LocalizedChatMessages
{
public string MapRevealed { get; init; } = "???"; //"The map for this floor has been revealed!";
public string AllTrapsRemoved { get; init; } = "???"; // "All the traps on this floor have disappeared!";

View File

@ -10,14 +10,14 @@ namespace Pal.Client.DependencyInjection
{
internal sealed class RepoVerification
{
public RepoVerification(ILogger<RepoVerification> logger, DalamudPluginInterface pluginInterface, ChatGui chatGui)
public RepoVerification(ILogger<RepoVerification> logger, DalamudPluginInterface pluginInterface, Chat chat)
{
logger.LogInformation("Install source: {Repo}", pluginInterface.SourceRepository);
if (!pluginInterface.IsDev
&& !pluginInterface.SourceRepository.StartsWith("https://raw.githubusercontent.com/carvelli/")
&& !pluginInterface.SourceRepository.StartsWith("https://github.com/carvelli/"))
{
chatGui.PalError(string.Format(Localization.Error_WrongRepository,
chat.Error(string.Format(Localization.Error_WrongRepository,
"https://github.com/carvelli/Dalamud-Plugins"));
throw new InvalidOperationException();
}

View File

@ -15,15 +15,15 @@ namespace Pal.Client.DependencyInjection
private readonly IPalacePalConfiguration _configuration;
private readonly RemoteApi _remoteApi;
private readonly StatisticsWindow _statisticsWindow;
private readonly ChatGui _chatGui;
private readonly Chat _chat;
public StatisticsService(IPalacePalConfiguration configuration, RemoteApi remoteApi,
StatisticsWindow statisticsWindow, ChatGui chatGui)
StatisticsWindow statisticsWindow, Chat chat)
{
_configuration = configuration;
_remoteApi = remoteApi;
_statisticsWindow = statisticsWindow;
_chatGui = chatGui;
_chat = chat;
}
public void ShowGlobalStatistics()
@ -35,7 +35,7 @@ namespace Pal.Client.DependencyInjection
{
if (!_configuration.HasRoleOnCurrentServer(RemoteApi.RemoteUrl, "statistics:view"))
{
_chatGui.PalError(Localization.Command_pal_stats_CurrentFloor);
_chat.Error(Localization.Command_pal_stats_CurrentFloor);
return;
}
@ -49,16 +49,16 @@ namespace Pal.Client.DependencyInjection
}
else
{
_chatGui.PalError(Localization.Command_pal_stats_UnableToFetchStatistics);
_chat.Error(Localization.Command_pal_stats_UnableToFetchStatistics);
}
}
catch (RpcException e) when (e.StatusCode == StatusCode.PermissionDenied)
{
_chatGui.PalError(Localization.Command_pal_stats_CurrentFloor);
_chat.Error(Localization.Command_pal_stats_CurrentFloor);
}
catch (Exception e)
{
_chatGui.PalError(e.ToString());
_chat.Error(e.ToString());
}
}
}

View File

@ -22,6 +22,7 @@ using Pal.Client.Configuration;
using Pal.Client.Database;
using Pal.Client.DependencyInjection;
using Pal.Client.DependencyInjection.Logging;
using Pal.Client.Extensions;
using Pal.Client.Net;
using Pal.Client.Properties;
using Pal.Client.Rendering;
@ -72,6 +73,7 @@ namespace Pal.Client
services.AddSingleton(clientState);
services.AddSingleton(gameGui);
services.AddSingleton(chatGui);
services.AddSingleton<Chat>();
services.AddSingleton(objectTable);
services.AddSingleton(framework);
services.AddSingleton(condition);
@ -151,9 +153,11 @@ namespace Pal.Client
{
using IDisposable? logScope = _logger.BeginScope("AsyncInit");
Chat? chat = null;
try
{
_logger.LogInformation("Starting async init");
chat = _serviceProvider.GetService<Chat>();
// initialize database
await using (var scope = _serviceProvider.CreateAsyncScope())
@ -191,7 +195,7 @@ namespace Pal.Client
catch (Exception e)
{
_logger.LogError(e, "Async load failed");
chatGui.PrintError($"Async loading failed: {e.GetType()}: {e.Message}");
chat?.Error($"Async loading failed: {e.GetType()}: {e.Message}");
}
});
}

View File

@ -75,7 +75,7 @@ namespace Pal.Client
/*
if (Service.Configuration.BetaKey == "VFX")
_chatGui.PalPrint($"{vfxPath} on {obj}");
_chat.PalPrint($"{vfxPath} on {obj}");
*/
if (obj is BattleChara bc && (bc.NameId == /* potd */ 5042 || bc.NameId == /* hoh */ 7395))

View File

@ -11,6 +11,7 @@ using System.Threading.Tasks;
using Pal.Client.Extensions;
using Pal.Client.Properties;
using Pal.Client.Configuration;
using Pal.Client.DependencyInjection;
namespace Pal.Client.Net
{
@ -68,7 +69,7 @@ namespace Pal.Client.Net
_logger.LogError("Account creation failed with error {Error}", createAccountReply.Error);
if (createAccountReply.Error == CreateAccountError.UpgradeRequired && !_warnedAboutUpgrade)
{
_chatGui.PalError(Localization.ConnectionError_OldVersion);
_chat.Error(Localization.ConnectionError_OldVersion);
_warnedAboutUpgrade = true;
}
return (false, string.Format(Localization.ConnectionError_CreateAccountFailed, createAccountReply.Error));
@ -123,7 +124,7 @@ namespace Pal.Client.Net
}
if (loginReply.Error == LoginError.UpgradeRequired && !_warnedAboutUpgrade)
{
_chatGui.PalError(Localization.ConnectionError_OldVersion);
_chat.Error(Localization.ConnectionError_OldVersion);
_warnedAboutUpgrade = true;
}
return (false, string.Format(Localization.ConnectionError_LoginFailed, loginReply.Error));
@ -181,7 +182,7 @@ namespace Pal.Client.Net
public bool IsLoggedIn { get; }
public string? AuthToken { get; }
public JwtClaims? Claims { get; }
public DateTimeOffset ExpiresAt => Claims?.ExpiresAt.Subtract(TimeSpan.FromMinutes(5)) ?? DateTimeOffset.MinValue;
private DateTimeOffset ExpiresAt => Claims?.ExpiresAt.Subtract(TimeSpan.FromMinutes(5)) ?? DateTimeOffset.MinValue;
public bool IsExpired => ExpiresAt < DateTimeOffset.UtcNow;
public bool IsValid => IsLoggedIn && !IsExpired;

View File

@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging;
using System;
using Dalamud.Game.Gui;
using Pal.Client.Configuration;
using Pal.Client.DependencyInjection;
namespace Pal.Client.Net
{
@ -19,7 +20,7 @@ namespace Pal.Client.Net
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<RemoteApi> _logger;
private readonly ChatGui _chatGui;
private readonly Chat _chat;
private readonly ConfigurationManager _configurationManager;
private readonly IPalacePalConfiguration _configuration;
@ -30,13 +31,13 @@ namespace Pal.Client.Net
public RemoteApi(
ILoggerFactory loggerFactory,
ILogger<RemoteApi> logger,
ChatGui chatGui,
Chat chat,
ConfigurationManager configurationManager,
IPalacePalConfiguration configuration)
{
_loggerFactory = loggerFactory;
_logger = logger;
_chatGui = chatGui;
_chat = chat;
_configurationManager = configurationManager;
_configuration = configuration;
}

View File

@ -26,19 +26,20 @@ namespace Pal.Client.Rendering
private readonly ILogger<SplatoonRenderer> _logger;
private readonly DebugState _debugState;
private readonly ClientState _clientState;
private readonly ChatGui _chatGui;
private readonly Chat _chat;
public SplatoonRenderer(
ILogger<SplatoonRenderer> logger,
DalamudPluginInterface pluginInterface,
IDalamudPlugin dalamudPlugin,
DebugState debugState,
ClientState clientState, ChatGui chatGui)
ClientState clientState,
Chat chat)
{
_logger = logger;
_debugState = debugState;
_clientState = clientState;
_chatGui = chatGui;
_chat = chat;
_logger.LogInformation("Initializing splatoon...");
ECommonsMain.Init(pluginInterface, dalamudPlugin, ECommons.Module.SplatoonAPI);
@ -100,6 +101,9 @@ namespace Pal.Client.Rendering
return new SplatoonElement(this, element);
}
// TODO This should be handled differently
// - make SimpleRenderer implement this
// - return error (if any) instead of using chat here
public void DrawDebugItems(Vector4 trapColor, Vector4 hoardColor)
{
try
@ -117,7 +121,7 @@ namespace Pal.Client.Rendering
elements.Cast<SplatoonElement>().Select(x => x.Delegate).ToArray(),
new[] { Environment.TickCount64 + 10000 }))
{
_chatGui.PalMessage("Could not draw markers :(");
_chat.Message("Could not draw markers :(");
}
}
}
@ -137,9 +141,9 @@ namespace Pal.Client.Rendering
string? pluginName = (string?)t.GetType().GetProperty("Name")?.GetValue(t);
if (assemblyName?.Name == "Splatoon" && pluginName != "Splatoon")
{
_chatGui.PalError(
_chat.Error(
$"Splatoon is installed under the plugin name '{pluginName}', which is incompatible with the Splatoon API.");
_chatGui.PalMessage(
_chat.Message(
"You need to install Splatoon from the official repository at https://github.com/NightmareXIV/MyDalamudPlugins.");
return;
}
@ -150,7 +154,7 @@ namespace Pal.Client.Rendering
// not relevant
}
_chatGui.PalError("Could not draw markers, is Splatoon installed and enabled?");
_chat.Error("Could not draw markers, is Splatoon installed and enabled?");
}
}

View File

@ -31,20 +31,20 @@ namespace Pal.Client.Scheduled
internal sealed class Handler : IQueueOnFrameworkThread.Handler<QueuedImport>
{
private readonly ChatGui _chatGui;
private readonly Chat _chat;
private readonly FloorService _floorService;
private readonly ImportService _importService;
private readonly ConfigWindow _configWindow;
public Handler(
ILogger<Handler> logger,
ChatGui chatGui,
Chat chat,
FloorService floorService,
ImportService importService,
ConfigWindow configWindow)
: base(logger)
{
_chatGui = chatGui;
_chat = chat;
_floorService = floorService;
_importService = importService;
_configWindow = configWindow;
@ -88,13 +88,13 @@ namespace Pal.Client.Scheduled
_logger.LogInformation(
$"Imported {import.ExportId} for {import.ImportedTraps} traps, {import.ImportedHoardCoffers} hoard coffers");
_chatGui.PalMessage(string.Format(Localization.ImportCompleteStatistics, import.ImportedTraps,
_chat.Message(string.Format(Localization.ImportCompleteStatistics, import.ImportedTraps,
import.ImportedHoardCoffers));
}
catch (Exception e)
{
_logger.LogError(e, "Import failed");
_chatGui.PalError(string.Format(Localization.Error_ImportFailed, e));
_chat.Error(string.Format(Localization.Error_ImportFailed, e));
}
}
@ -104,14 +104,14 @@ namespace Pal.Client.Scheduled
{
_logger.LogError(
"Import: Different version in export file, {ExportVersion} != {ConfiguredVersion}", import.Export.ExportVersion, ExportConfig.ExportVersion);
_chatGui.PalError(Localization.Error_ImportFailed_IncompatibleVersion);
_chat.Error(Localization.Error_ImportFailed_IncompatibleVersion);
return false;
}
if (!Guid.TryParse(import.Export.ExportId, out Guid exportId) || exportId == Guid.Empty)
{
_logger.LogError("Import: Invalid export id '{Id}'", import.Export.ExportId);
_chatGui.PalError(Localization.Error_ImportFailed_InvalidFile);
_chat.Error(Localization.Error_ImportFailed_InvalidFile);
return false;
}
@ -121,7 +121,7 @@ namespace Pal.Client.Scheduled
{
// If we allow for backups as import/export, this should be removed
_logger.LogError("Import: No server URL");
_chatGui.PalError(Localization.Error_ImportFailed_InvalidFile);
_chat.Error(Localization.Error_ImportFailed_InvalidFile);
return false;
}

View File

@ -41,7 +41,7 @@ namespace Pal.Client.Windows
private readonly FrameworkService _frameworkService;
private readonly FloorService _floorService;
private readonly DebugState _debugState;
private readonly ChatGui _chatGui;
private readonly Chat _chat;
private readonly RemoteApi _remoteApi;
private readonly ImportService _importService;
@ -74,7 +74,7 @@ namespace Pal.Client.Windows
FrameworkService frameworkService,
FloorService floorService,
DebugState debugState,
ChatGui chatGui,
Chat chat,
RemoteApi remoteApi,
ImportService importService)
: base(WindowId)
@ -88,7 +88,7 @@ namespace Pal.Client.Windows
_frameworkService = frameworkService;
_floorService = floorService;
_debugState = debugState;
_chatGui = chatGui;
_chat = chat;
_remoteApi = remoteApi;
_importService = importService;
@ -504,17 +504,17 @@ namespace Pal.Client.Windows
await using var output = File.Create(destinationPath);
export.WriteTo(output);
_chatGui.PalMessage($"Export saved as {destinationPath}.");
_chat.Message($"Export saved as {destinationPath}.");
}
else
{
_chatGui.PalError("Export failed due to server error.");
_chat.Error("Export failed due to server error.");
}
}
catch (Exception e)
{
_logger.LogError(e, "Export failed");
_chatGui.PalError($"Export failed: {e}");
_chat.Error($"Export failed: {e}");
}
});
}