DP-PatMe2Mqtt/PatMe2Mqtt/Service.cs
2024-07-02 10:15:50 +02:00

111 lines
3.8 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;
using Dalamud.Plugin.Services;
namespace PatMe2Mqtt
{
public sealed class Service
{
public Service()
{
// THIS. IS. UGLY.
try
{
if (typeof(PluginServiceAttribute).Assembly.GetType("Dalamud.Service`1") is not { } serviceContainerContainer)
{
PluginLog.Information("PatMe2Mqtt couldn't find the service container types.");
return;
}
if (typeof(PluginServiceAttribute).Assembly.GetType("Dalamud.Plugin.Internal.PluginManager") is not { } pluginManagerType)
{
PluginLog.Information("PatMe2Mqtt 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.Information("PatMe2Mqtt 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.Information("PatMe2Mqtt couldn't obtain the plugin manager.");
return;
}
if (pluginManagerType.GetProperty("InstalledPlugins") is not { } installedPluginsProperty)
{
PluginLog.Information("PatMe2Mqtt couldn't obtain the plugin list property.");
return;
}
GetPluginInstance = name =>
{
if (installedPluginsProperty?.GetValue(manager) is not IList installedPlugins)
{
PluginLog.Information("PatMe2Mqtt 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.Information($"PatMe2Mqtt 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 IDalamudPluginInterface PluginInterface { get; private set; } = null!;
[PluginService]
public static ICommandManager CommandManager { get; private set; } = null!;
[PluginService]
public static IFramework Framework { get; private set; } = null!;
[PluginService]
public static IClientState ClientState { get; private set; } = null!;
[PluginService]
public static IPluginLog PluginLog { get; private set; } = null!;
public static Func<string, object?>? GetPluginInstance { get; private set; }
}
}