-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathPluginImporter.cs
224 lines (194 loc) · 8.47 KB
/
PluginImporter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using IW4MAdmin.Application.API.Master;
#if DEBUG
using Microsoft.Extensions.DependencyModel;
#endif
using Microsoft.Extensions.Logging;
using SharedLibraryCore;
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Interfaces;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace IW4MAdmin.Application.Plugin
{
/// <summary>
/// implementation of IPluginImporter
/// discovers plugins and script plugins
/// </summary>
public class PluginImporter : IPluginImporter
{
private IEnumerable<PluginSubscriptionContent> _pluginSubscription;
private const string PluginDir = "Plugins";
private const string PluginV2Match = "^ *((?:var|const|let) +init)|function init";
private readonly ILogger _logger;
private readonly IRemoteAssemblyHandler _remoteAssemblyHandler;
private readonly IMasterApi _masterApi;
private readonly ApplicationConfiguration _appConfig;
private static readonly Type[] FilterTypes =
{
typeof(IPlugin),
typeof(IPluginV2),
typeof(Command),
typeof(IBaseConfiguration)
};
public PluginImporter(ILogger<PluginImporter> logger, ApplicationConfiguration appConfig, IMasterApi masterApi,
IRemoteAssemblyHandler remoteAssemblyHandler)
{
_logger = logger;
_masterApi = masterApi;
_remoteAssemblyHandler = remoteAssemblyHandler;
_appConfig = appConfig;
}
/// <summary>
/// discovers all the script plugins in the plugins dir
/// </summary>
/// <returns></returns>
public IEnumerable<(Type, string)> DiscoverScriptPlugins()
{
var pluginDir = $"{Utilities.OperatingDirectory}{PluginDir}{Path.DirectorySeparatorChar}";
if (!Directory.Exists(pluginDir))
{
return Enumerable.Empty<(Type, string)>();
}
var scriptPluginFiles =
Directory.GetFiles(pluginDir, "*.js").AsEnumerable().Union(GetRemoteScripts()).ToList();
var bothVersionPlugins = scriptPluginFiles.Select(fileName =>
{
_logger.LogDebug("Discovered script plugin {FileName}", fileName);
try
{
var fileContents = File.ReadAllLines(fileName);
var isValidV2 = fileContents.Any(line => Regex.IsMatch(line, PluginV2Match));
return isValidV2 ? (typeof(IPluginV2), fileName) : (typeof(IPlugin), fileName);
}
catch
{
return (typeof(IPlugin), fileName);
}
}).ToList();
return bothVersionPlugins;
}
/// <summary>
/// discovers all the C# assembly plugins and commands
/// </summary>
/// <returns></returns>
public (IEnumerable<Type>, IEnumerable<Type>, IEnumerable<Type>) DiscoverAssemblyPluginImplementations()
{
var pluginDir = $"{Utilities.OperatingDirectory}{PluginDir}{Path.DirectorySeparatorChar}";
var pluginTypes = new List<Type>();
var commandTypes = new List<Type>();
var configurationTypes = new List<Type>();
if (!Directory.Exists(pluginDir))
{
return (pluginTypes, commandTypes, configurationTypes);
}
var dllFileNames = Directory.GetFiles(pluginDir, "*.dll");
_logger.LogDebug("Discovered {Count} potential plugin assemblies", dllFileNames.Length);
if (dllFileNames.Length is 0)
{
return (pluginTypes, commandTypes, configurationTypes);
}
#if DEBUG
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(asm => asm.GetName().Name);
var references = DependencyContext.Default?.GetDefaultAssemblyNames().Select(x => x.Name) ?? [];
var validAssemblies = references.Except(loadedAssemblies)
.Where(asm => !asm.StartsWith("Microsoft"))
.Where(asm => !asm.StartsWith("System"))
.Distinct();
var reloadableAssemblies = validAssemblies.Select(Assembly.Load);
#endif
// we only want to load the most recent assembly in case of duplicates
var assemblies = dllFileNames.Select(fileName => fileName).Select(Assembly.LoadFrom)
.Union(GetRemoteAssemblies())
#if DEBUG
.Union(reloadableAssemblies)
#endif
.GroupBy(assembly => assembly.FullName).Select(assembly =>
assembly.OrderByDescending(asm => asm.GetName().Version).First());
var eligibleAssemblyTypes = assemblies.Concat(AppDomain.CurrentDomain.GetAssemblies()
.Where(asm => !new[] { "IW4MAdmin", "SharedLibraryCore", "Stats" }.Contains(asm.GetName().Name)))
.SelectMany(asm =>
{
try
{
return asm.GetTypes();
}
catch
{
return [];
}
}).Where(type =>
FilterTypes.Any(filterType => type.GetInterface(filterType.Name, false) != null) ||
(type.IsClass && FilterTypes.Contains(type.BaseType)));
foreach (var assemblyType in eligibleAssemblyTypes)
{
var isPlugin =
(assemblyType.GetInterface(nameof(IPlugin), false) ??
assemblyType.GetInterface(nameof(IPluginV2), false)) != null &&
(!assemblyType.Namespace?.StartsWith(nameof(SharedLibraryCore)) ?? false);
if (isPlugin)
{
pluginTypes.Add(assemblyType);
continue;
}
var isCommand = assemblyType.IsClass && assemblyType.BaseType == typeof(Command) &&
(!assemblyType.Namespace?.StartsWith(nameof(SharedLibraryCore)) ?? false);
if (isCommand)
{
commandTypes.Add(assemblyType);
continue;
}
var isConfiguration = assemblyType.IsClass &&
assemblyType.GetInterface(nameof(IBaseConfiguration), false) != null &&
(!assemblyType.Namespace?.StartsWith(nameof(SharedLibraryCore)) ?? false);
if (isConfiguration)
{
configurationTypes.Add(assemblyType);
}
}
_logger.LogDebug("Discovered {Count} plugin implementations", pluginTypes.Count);
_logger.LogDebug("Discovered {Count} plugin command implementations", commandTypes.Count);
_logger.LogDebug("Discovered {Count} plugin configuration implementations", configurationTypes.Count);
return (pluginTypes, commandTypes, configurationTypes);
}
private IEnumerable<Assembly> GetRemoteAssemblies()
{
try
{
_pluginSubscription ??= _masterApi
.GetPluginSubscription(_appConfig.Id, _appConfig.SubscriptionId).Result;
return _remoteAssemblyHandler.DecryptAssemblies(_pluginSubscription
.Where(sub => sub.Type == PluginType.Binary).Select(sub => sub.Content).ToArray());
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not load remote assemblies");
return Enumerable.Empty<Assembly>();
}
}
private IEnumerable<string> GetRemoteScripts()
{
try
{
_pluginSubscription ??= _masterApi
.GetPluginSubscription(_appConfig.Id, _appConfig.SubscriptionId).Result;
return _remoteAssemblyHandler.DecryptScripts(_pluginSubscription
.Where(sub => sub.Type == PluginType.Script).Select(sub => sub.Content).ToArray());
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not load remote scripts");
return Enumerable.Empty<string>();
}
}
}
public enum PluginType
{
Binary,
Script
}
}