-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandManager.cs
More file actions
517 lines (453 loc) · 22.6 KB
/
CommandManager.cs
File metadata and controls
517 lines (453 loc) · 22.6 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
// -----------------------------------------------------------------------
// <copyright file="CommandManager.cs" company="Redforce04">
// Copyright (c) Redforce04. All rights reserved.
// Licensed under the CC BY-SA 3.0 license.
// </copyright>
// -----------------------------------------------------------------------
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
namespace AdvancedCommandLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using Attributes;
using CommandSystem;
using Contexts.Helpers;
using Enums;
using GameCommandModules.Processors;
using LabApi.Features.Console;
using RemoteAdmin;
using Trackers;
/// <summary>
/// The main command manager.
/// </summary>
public class CommandManager
{
private CommandManager()
{
}
/// <summary>
/// Gets the main instance of the Command Manager. Make sure to initialize by calling <see cref="LoadCommandManager"/> otherwise it will be null.
/// </summary>
public static CommandManager Instance { get; private set; } = null!;
/// <summary>
/// Gets or sets a value that indicates if debug logs should be shown.
/// </summary>
public static LoggingMode DebugMode { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the missing required permission branches will be shown when a user doesn't have permission to execute the command.
/// </summary>
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public static bool ShowPermissionsBranches { get; set; }
/// <summary>
/// Gets a list containing all the registered commands.
/// </summary>
internal Dictionary<int, CommandTracker> RegisteredCommands { get; private set; } = new();
private static RemoteAdminCommandHandler RemoteAdminCommandHandler => CommandProcessor.RemoteAdminCommandHandler;
private static GameConsoleCommandHandler GameConsoleCommandHandler => GameCore.Console.singleton.ConsoleCommandHandler;
private static ClientCommandHandler ClientCommandHandler => QueryProcessor.DotCommandHandler;
/// <summary>
/// Loads the command manager and registers all commands.
/// </summary>
public static void LoadCommandManager()
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (Instance is not null)
{
Logger.Warn("The CommandManager has already been loaded.");
return;
}
Instance = new();
Logger.Debug("Loading All Commands.", DebugMode >= LoggingMode.Debug);
Instance.LoadAllCommands();
}
/// <summary>
/// Unloads the command manager and unregisters all loaded commands.
/// </summary>
public static void UnloadCommandManager()
{
foreach (CommandTracker? cmdTracker in Instance.RegisteredCommands.Values.Where(x => x.ParentTrackerInstance is null).ToList())
{
try
{
Instance.UnregisterCommandsRecursive(cmdTracker, 0);
}
catch (Exception ex)
{
Logger.Warn($"Could not unregister command {cmdTracker.Name} because an error occured while trying to unregister the command from a game command handler.");
Logger.Debug($"Exception: {ex}", DebugMode >= LoggingMode.Debug);
}
}
Instance.RegisteredCommands = null;
Instance = null;
}
private void UnregisterCommandsRecursive(CommandTracker commandTracker, int depth)
{
if (depth >= 10)
{
Logger.Warn("Unregister search has reached a depth of 10 or more. This is bad and likely a bug.");
return;
}
if (commandTracker is ParentCommandTracker parentCommandTracker)
{
try
{
if (parentCommandTracker.GameCommandInstance is ParentCommandProcessor parentProcessor)
{
foreach (CommandTracker childCommandTracker in parentCommandTracker.ChildCommands)
{
try
{
if (childCommandTracker is ParentCommandTracker parentChildCommandTracker)
{
this.UnregisterCommandsRecursive(parentChildCommandTracker, depth + 1);
}
switch (childCommandTracker.GameCommandInstance)
{
case ParentCommandProcessor childParentProcessor:
parentProcessor.UnregisterCommand(childParentProcessor);
break;
case ChildCommandProcessor childCommandProcessor:
parentProcessor.UnregisterCommand(childCommandProcessor);
break;
}
childCommandTracker.UpdateParentTracker(null);
RegisteredCommands.Remove(childCommandTracker.Id);
}
catch (Exception)
{
// Unused.
}
}
}
parentCommandTracker.UpdateChildren([]);
parentCommandTracker.UpdateParentTracker(null);
}
catch (Exception)
{
// Unused.
}
}
if (depth != 0)
{
return;
}
try
{
if (commandTracker.HandlerType.HasFlag(CommandHandlerType.ClientConsole))
{
ClientCommandHandler.UnregisterCommand(commandTracker.GameCommandInstance);
}
if (commandTracker.HandlerType.HasFlag(CommandHandlerType.RemoteAdmin))
{
RemoteAdminCommandHandler.UnregisterCommand(commandTracker.GameCommandInstance);
}
if (commandTracker.HandlerType.HasFlag(CommandHandlerType.GameConsole))
{
GameConsoleCommandHandler.UnregisterCommand(commandTracker.GameCommandInstance);
}
}
catch (Exception)
{
// Unused.
}
}
private void LogCommandTree()
{
if (DebugMode < LoggingMode.Insanity)
{
return;
}
try
{
StringBuilder builder = new();
builder.AppendLine($"Registered Commands:");
foreach (CommandTracker tracker in RegisteredCommands.Values.Where(x => x.ParentTrackerInstance is null))
{
CommandTrackerTreeSearcher.SearchResult searchResult = CommandTrackerTreeSearcher.RecursivelySearchCommand(tracker, 0);
CommandTrackerTreeSearcher.RecursivelyBuildString(ref builder, searchResult, 0);
}
Logger.Debug(builder.ToString());
}
catch (Exception e)
{
Logger.Debug($"An error has occured while trying to log the command tree.\nException: {e}");
}
}
private void LoadAllCommands()
{
Logger.Debug("Searching Assemblies.", DebugMode >= LoggingMode.Debug);
try
{
this.SearchAssemblies();
}
catch (Exception e)
{
Logger.Warn("An error has occured while searching assemblies.");
Logger.Debug($"Exception: {e}", DebugMode >= LoggingMode.Insanity);
}
Logger.Debug("Assigning Child Commands.", DebugMode >= LoggingMode.Debug);
try
{
this.AssignChildCommands();
}
catch (Exception e)
{
Logger.Warn("An error has occured while assigning child commands.");
Logger.Debug($"Exception: {e}", DebugMode >= LoggingMode.Insanity);
}
this.LogCommandTree();
Logger.Debug("Initializing Game Commands.", DebugMode >= LoggingMode.Debug);
try
{
this.InitializeGameCommands();
}
catch (Exception e)
{
Logger.Warn("An error has occured while Initializing game commands.");
Logger.Debug($"Exception: {e}", DebugMode >= LoggingMode.Insanity);
}
Logger.Debug("Registering Game Commands.", DebugMode >= LoggingMode.Debug);
try
{
this.RegisterGameCommands();
}
catch (Exception e)
{
Logger.Warn("An error has occured while registering game commands.");
Logger.Debug($"Exception: {e}", DebugMode >= LoggingMode.Insanity);
}
Logger.Info($"{RegisteredCommands.Count} Commands Loaded.");
}
private void SearchAssemblies()
{
Logger.Debug($"[===== Search Assembly Module =====] Searching for all eligible commands.", DebugMode >= LoggingMode.Ludicrous);
// Foreach loaded plugin assembly we check all eligible methods for either a ParentCommandAttribute and a CommandAttribute.
foreach (Assembly pluginAssembly in LabApi.Loader.PluginLoader.Plugins.Values)
{
// Get all methods that are Public, Static, and Invokable
IEnumerable<MethodInfo> search = pluginAssembly.GetTypes().SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod));
foreach (MethodInfo method in search)
{
try
{
// Check to see if it has a RequirePermissionsAttribute and if it does, register a PermissionsTracker to track the required permissions.
PermissionsTracker? permTracker = this.FindAttributes<RequirePermissionsAttribute>(method) is { Count: > 0 } permsAtr ? new PermissionsTracker(permsAtr) : null;
// Check the method for CommandAttribute
if (this.FindAttribute<CommandAttribute>(method) is not { } cmdAtr)
{
continue;
}
// Create a tracker to track the command.
CommandTracker tracker = cmdAtr is ParentCommandAttribute ? new ParentCommandTracker()
{
Name = cmdAtr.Name, Description = cmdAtr.Description, Aliases = cmdAtr.Aliases, Usages = cmdAtr.Usages,
HandlerType = cmdAtr.HandlerType, PermissionsRequirementTracker = permTracker, Method = method, Assembly = pluginAssembly,
}
: new CommandTracker()
{
Name = cmdAtr.Name, Description = cmdAtr.Description, Aliases = cmdAtr.Aliases, Usages = cmdAtr.Usages,
HandlerType = cmdAtr.HandlerType, PermissionsRequirementTracker = permTracker, Method = method, Assembly = pluginAssembly,
};
if (tracker is ParentCommandTracker parentTracker && this.FindAttribute<LoadGeneratedCommandsExecutorAttribute>(method) is { Method: not null } loadExecutor)
{
parentTracker.LoadGeneratedCommandsExecutor = loadExecutor.Method;
}
// Then register the tracker in our tracking lists.
this.RegisteredCommands[tracker.Id] = tracker;
Logger.Debug($"[Found {(tracker is ParentCommandTracker ? "Parent" : "Child ")} Command] Name: \"{tracker.Name}\" [{tracker.Id}]", DebugMode >= LoggingMode.Ludicrous);
}
catch (Exception)
{
Logger.Warn($"An error has occured ");
}
}
}
Logger.Debug($"Resulting SearchAssemblies: [Commands: {RegisteredCommands.Count}]", DebugMode >= LoggingMode.Ludicrous);
}
private T? FindAttribute<T>(MethodInfo method)
where T : Attribute
{
if (Attribute.GetCustomAttribute(method, typeof(T)) is T attribute)
{
return attribute;
}
return null;
}
[MemberNotNull]
private List<T> FindAttributes<T>(MethodInfo method)
where T : Attribute
{
if (Attribute.GetCustomAttributes(method, typeof(T)) is T[] attributes)
{
return attributes.ToList();
}
return new List<T>();
}
private void AssignChildCommands()
{
Logger.Debug($"[===== Assign Child Command Module =====] Assigning Parents & Children to any eligible commands.", DebugMode >= LoggingMode.Ludicrous);
// Foreach Command Check if it has a ParentAttribute, then ensure the parent is actually valid. Then associate both the parents and the children with each other.
foreach (CommandTracker immutableTracker in RegisteredCommands.Values.ToList())
{
CommandTracker tracker = immutableTracker;
Logger.Debug($"[Checking {(tracker is ParentCommandTracker ? "Parent" : "Child")}] \"{tracker.Name}\".", DebugMode >= LoggingMode.Ludicrous);
if (FindAttribute<ParentAttribute>(tracker.Method) is { } parentAtr)
{
if (!TryGetParentCommand(ref tracker, parentAtr, out ParentCommandTracker? parent))
{
continue;
}
tracker.UpdateParentTracker(parent!);
parent!.AddChild(tracker);
this.RegisteredCommands[tracker.Id] = tracker;
this.RegisteredCommands[parent.Id] = parent;
continue;
}
// If no parents, then add to list as a base parent command.
this.RegisteredCommands[tracker.Id] = tracker;
Logger.Debug($"====> No Parents Found. Base Command.", DebugMode >= LoggingMode.Ludicrous);
}
}
[MemberNotNullWhen(true)]
private bool TryGetParentCommand(ref CommandTracker tracker, ParentAttribute parentAtr, out ParentCommandTracker? parentCommandTracker)
{
parentCommandTracker = null;
MethodInfo? method = parentAtr.ParentBaseType.GetMethod(name: parentAtr.ParentName, bindingAttr: BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static);
if (method is null)
{
Logger.Warn($"Could not find the specified parent command for the command \"{tracker.Name}\". The command and any children will not be registered.");
Logger.Debug($"Method \"{parentAtr.ParentBaseType.FullName}.{parentAtr.ParentName}(ParentContext ctx)\" could not be found. Remember that it must be a public, static, method with only ParentContext as the parameters.", DebugMode >= LoggingMode.Debug);
return false;
}
if (Attribute.GetCustomAttribute(method, typeof(ParentCommandAttribute)) is not ParentCommandAttribute)
{
Logger.Warn($"The parent command for command \"{tracker.Name}\" is missing the ParentCommandAttribute. The command and any children will not be registered.");
Logger.Debug($"Method \"{parentAtr.ParentBaseType.FullName}.{parentAtr.ParentName}(ParentContext ctx)\" did not have the [ParentCommand] Attribute.", DebugMode >= LoggingMode.Debug);
return false;
}
ParentCommandTracker? parent = RegisteredCommands.Values.FirstOrDefault(x => x is ParentCommandTracker && x.Method == method) as ParentCommandTracker;
if (parent is null)
{
Logger.Warn($"The parent command for command \"{tracker.Name}\" Could not be found. This is likely due to a bug. The command and any children will not be registered.");
Logger.Debug($"Method \"{parentAtr.ParentBaseType.FullName}.{parentAtr.ParentName}(ParentContext ctx)\" was found, however it was not registered which should have already occured by this point. This is likely a framework bug.", DebugMode >= LoggingMode.Debug);
return false;
}
parentCommandTracker = parent;
Logger.Debug($"====> Parent Found: \"{parent.Name}\".", DebugMode >= LoggingMode.Ludicrous);
return true;
}
private void InitializeGameCommands()
{
Logger.Debug($"[===== Initialize Game Commands Module =====] Initializing Child & Parent Command Processors.", DebugMode >= LoggingMode.Ludicrous);
try
{
foreach (CommandTracker cmd in RegisteredCommands.Values.ToList())
{
if(cmd is ParentCommandTracker parent)
{
this.RegisteredCommands[cmd.Id].GameCommandInstance = new ParentCommandProcessor(parent);
}
else
{
this.RegisteredCommands[cmd.Id].GameCommandInstance = new ChildCommandProcessor(cmd);
}
}
// Load generated commands after all the instances are fully initialized.
foreach (CommandTracker x in RegisteredCommands.Values)
{
if(x.GameCommandInstance is not ParentCommandProcessor parent)
{
continue;
}
parent.LoadGeneratedCommands();
}
}
catch (Exception e)
{
Logger.Error("Could not initialize game commands because of an error.");
Logger.Debug($"Exception: \n{e}", DebugMode >= LoggingMode.Debug);
}
Logger.Debug($"Resulting InitializeGameCommands: [Commands: {RegisteredCommands.Count}]", DebugMode >= LoggingMode.Ludicrous);
}
private void RegisterGameCommands()
{
Logger.Debug($"[===== Register Game Commands Module =====] Registering Parent & Child Command Processors to their relevant game command handler modules.", DebugMode >= LoggingMode.Ludicrous);
string[] gameConsoleAliases = GameConsoleCommandHandler.AllCommands.SelectMany(x => x.Aliases ?? []).ToArray();
string[] gameConsoleCommands = GameConsoleCommandHandler.AllCommands.Select(x => x.Command ?? string.Empty).ToArray();
string[] clientConsoleAliases = ClientCommandHandler.AllCommands.SelectMany(x => x.Aliases ?? []).ToArray();
string[] clientConsoleCommands = ClientCommandHandler.AllCommands.Select(x => x.Command ?? string.Empty).ToArray();
string[] remoteAdminAliases = RemoteAdminCommandHandler.AllCommands.SelectMany(x => x.Aliases ?? []).ToArray();
string[] remoteAdminCommands = RemoteAdminCommandHandler.AllCommands.Select(x => x.Command ?? string.Empty).ToArray();
Logger.Debug($"All currently registered commands:", DebugMode >= LoggingMode.Ludicrous);
foreach (CommandTracker cmd in RegisteredCommands.Values)
{
Logger.Debug($"====> [{(cmd is ParentCommandTracker { } parent ? $"Parent - {parent.ChildCommands.Count} Children" : "Child")}] {cmd.Name} - {(cmd.ParentTrackerInstance is null ? "[Base Command]" : $"(Nested Command - Parent: {cmd.ParentTrackerInstance?.Name})")} ", DebugMode >= LoggingMode.Ludicrous);
}
Logger.Debug($"Registering Base Commands:", DebugMode >= LoggingMode.Ludicrous);
foreach (CommandTracker cmd in RegisteredCommands.Values.Where(x => x.ParentTrackerInstance is null))
{
string modes = string.Empty;
try
{
if (cmd.HandlerType.HasFlag(CommandHandlerType.ClientConsole))
{
if (clientConsoleCommands.Any(x => string.Equals(cmd.Name, x, StringComparison.CurrentCultureIgnoreCase)))
{
Logger.Warn($"Could not register child command \"{cmd.Name}\" to ClientConsoleCommandHandler because a command with a similar name already exists.");
}
else if (clientConsoleAliases.Any(x => cmd.Aliases.Any(y => string.Equals(y, x, StringComparison.CurrentCultureIgnoreCase))))
{
Logger.Warn($"Could not register child command \"{cmd.Name}\" to ClientConsoleCommandHandler because a command with a similar alias already exists.");
}
else
{
modes += " [Client Console]";
ClientCommandHandler.RegisterCommand(cmd.GameCommandInstance);
}
}
if (cmd.HandlerType.HasFlag(CommandHandlerType.RemoteAdmin))
{
if (remoteAdminCommands.Any(x => string.Equals(cmd.Name, x, StringComparison.CurrentCultureIgnoreCase)))
{
Logger.Warn($"Could not register child command \"{cmd.Name}\" to RemoteAdminCommandHandler because a command with a similar name already exists.");
}
else if (remoteAdminAliases.Any(x => cmd.Aliases.Any(y => string.Equals(y, x, StringComparison.CurrentCultureIgnoreCase))))
{
Logger.Warn($"Could not register child command \"{cmd.Name}\" to RemoteAdminCommandHandler because a command with a similar alias already exists.");
}
else
{
modes += " [Remote Admin]";
RemoteAdminCommandHandler.RegisterCommand(cmd.GameCommandInstance);
}
}
if (cmd.HandlerType.HasFlag(CommandHandlerType.GameConsole))
{
if (gameConsoleCommands.Any(x => string.Equals(cmd.Name, x, StringComparison.CurrentCultureIgnoreCase)))
{
Logger.Warn($"Could not register child command \"{cmd.Name}\" to GameConsoleCommandHandler because a command with a similar name already exists.");
}
else if (gameConsoleAliases.Any(x => cmd.Aliases.Any(y => string.Equals(y, x, StringComparison.CurrentCultureIgnoreCase))))
{
Logger.Warn($"Could not register child command \"{cmd.Name}\" to GameConsoleCommandHandler because a command with a similar alias already exists.");
}
else
{
modes += " [Game Console]";
GameConsoleCommandHandler.RegisterCommand(cmd.GameCommandInstance);
}
}
}
catch (Exception e)
{
Logger.Warn($"Could not register game command {cmd.Name} due to an error.");
Logger.Debug($"Error: \n{e}", DebugMode >= LoggingMode.Debug);
}
Logger.Debug($"====> \"{cmd.Name}\"{modes}", DebugMode >= LoggingMode.Ludicrous);
}
}
}
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.