DP-PatMe2Mqtt/PatMe2Mqtt/Service.cs
2023-05-26 15:55:33 +02:00

107 lines
3.7 KiB
C#

using Dalamud.Data;
using Dalamud.Game;
using Dalamud.Game.ClientState;
using Dalamud.Game.ClientState.Objects;
using Dalamud.Game.Command;
using Dalamud.Game.Gui;
using Dalamud.Game.Text;
using Dalamud.IoC;
using Dalamud.Logging;
using Dalamud.Plugin;
using System.Reflection;
using System;
using System.Collections;
namespace PatMe2Mqtt
{
public sealed class Service
{
public Service()
{
// THIS. IS. UGLY.
try
{
if (typeof(PluginServiceAttribute).Assembly.GetType("Dalamud.Service`1") is not { } serviceContainerContainer)
{
PluginLog.LogInformation("PenumbraCmd couldn't find the service container types.");
return;
}
if (typeof(PluginServiceAttribute).Assembly.GetType("Dalamud.Plugin.Internal.PluginManager") is not { } pluginManagerType)
{
PluginLog.LogInformation("PenumbraCmd couldn't find the plugin manager type.");
return;
}
if (typeof(PluginServiceAttribute).Assembly.GetType("Dalamud.Plugin.Internal.Types.LocalPlugin") is not { } localPluginType ||
localPluginType.GetField("instance", BindingFlags.NonPublic | BindingFlags.Instance) is not { } localPluginInstanceField)
{
PluginLog.LogInformation("PenumbraCmd couldn't find the local plugin type or important members.");
return;
}
serviceContainerContainer = serviceContainerContainer.MakeGenericType(pluginManagerType);
if (serviceContainerContainer.GetMethod("Get")?.Invoke(null, Array.Empty<object>()) is not object manager)
{
PluginLog.LogInformation("PenumbraCmd couldn't obtain the plugin manager.");
return;
}
if (pluginManagerType.GetProperty("InstalledPlugins") is not { } installedPluginsProperty)
{
PluginLog.LogInformation("PenumbraCmd couldn't obtain the plugin list property.");
return;
}
GetPluginInstance = name =>
{
if (installedPluginsProperty?.GetValue(manager) is not IList installedPlugins)
{
PluginLog.LogInformation("PenumbraCmd couldn't obtain the plugin list.");
return null;
}
foreach (var plugin in installedPlugins)
{
if (localPluginInstanceField.GetValue(plugin) is { } instance && instance.GetType().Assembly.GetName().Name == name)
{
return instance;
}
}
return null;
};
}
catch (Exception e)
{
PluginLog.LogInformation($"PenumbraCmd couldn't obtain the plugin manager service: {e}");
}
}
public static Plugin Plugin { get; internal set; } = null!;
public static PatMeProxyApi.PatMe PatMe { get; internal set; } = null!;
[PluginService]
public static DalamudPluginInterface PluginInterface { get; private set; } = null!;
[PluginService]
public static CommandManager CommandManager { get; private set; } = null!;
[PluginService]
public static Framework Framework { get; private set; } = null!;
[PluginService]
public static ClientState ClientState { get; private set; } = null!;
public static Func<string, object?>? GetPluginInstance { get; private set; }
}
}