You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

CommandService.cs 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using Discord.Commands.Builders;
  2. using Discord.Logging;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Collections.Immutable;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace Discord.Commands
  12. {
  13. public class CommandService
  14. {
  15. public event Func<LogMessage, Task> Log { add { _logEvent.Add(value); } remove { _logEvent.Remove(value); } }
  16. internal readonly AsyncEvent<Func<LogMessage, Task>> _logEvent = new AsyncEvent<Func<LogMessage, Task>>();
  17. public event Func<CommandInfo, ICommandContext, IResult, Task> CommandExecuted { add { _commandExecutedEvent.Add(value); } remove { _commandExecutedEvent.Remove(value); } }
  18. internal readonly AsyncEvent<Func<CommandInfo, ICommandContext, IResult, Task>> _commandExecutedEvent = new AsyncEvent<Func<CommandInfo, ICommandContext, IResult, Task>>();
  19. private readonly SemaphoreSlim _moduleLock;
  20. private readonly ConcurrentDictionary<Type, ModuleInfo> _typedModuleDefs;
  21. private readonly ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>> _typeReaders;
  22. private readonly ConcurrentDictionary<Type, TypeReader> _defaultTypeReaders;
  23. private readonly ImmutableList<Tuple<Type, Type>> _entityTypeReaders; //TODO: Candidate for C#7 Tuple
  24. private readonly HashSet<ModuleInfo> _moduleDefs;
  25. private readonly CommandMap _map;
  26. internal readonly bool _caseSensitive, _throwOnError, _ignoreExtraArgs;
  27. internal readonly char _separatorChar;
  28. internal readonly RunMode _defaultRunMode;
  29. internal readonly Logger _cmdLogger;
  30. internal readonly LogManager _logManager;
  31. public IEnumerable<ModuleInfo> Modules => _moduleDefs.Select(x => x);
  32. public IEnumerable<CommandInfo> Commands => _moduleDefs.SelectMany(x => x.Commands);
  33. public ILookup<Type, TypeReader> TypeReaders => _typeReaders.SelectMany(x => x.Value.Select(y => new { y.Key, y.Value })).ToLookup(x => x.Key, x => x.Value);
  34. public CommandService() : this(new CommandServiceConfig()) { }
  35. public CommandService(CommandServiceConfig config)
  36. {
  37. _caseSensitive = config.CaseSensitiveCommands;
  38. _throwOnError = config.ThrowOnError;
  39. _ignoreExtraArgs = config.IgnoreExtraArgs;
  40. _separatorChar = config.SeparatorChar;
  41. _defaultRunMode = config.DefaultRunMode;
  42. if (_defaultRunMode == RunMode.Default)
  43. throw new InvalidOperationException("The default run mode cannot be set to Default.");
  44. _logManager = new LogManager(config.LogLevel);
  45. _logManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);
  46. _cmdLogger = _logManager.CreateLogger("Command");
  47. _moduleLock = new SemaphoreSlim(1, 1);
  48. _typedModuleDefs = new ConcurrentDictionary<Type, ModuleInfo>();
  49. _moduleDefs = new HashSet<ModuleInfo>();
  50. _map = new CommandMap(this);
  51. _typeReaders = new ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>>();
  52. _defaultTypeReaders = new ConcurrentDictionary<Type, TypeReader>();
  53. foreach (var type in PrimitiveParsers.SupportedTypes)
  54. {
  55. _defaultTypeReaders[type] = PrimitiveTypeReader.Create(type);
  56. _defaultTypeReaders[typeof(Nullable<>).MakeGenericType(type)] = NullableTypeReader.Create(type, _defaultTypeReaders[type]);
  57. }
  58. _defaultTypeReaders[typeof(string)] =
  59. new PrimitiveTypeReader<string>((string x, out string y) => { y = x; return true; }, 0);
  60. var entityTypeReaders = ImmutableList.CreateBuilder<Tuple<Type, Type>>();
  61. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IMessage), typeof(MessageTypeReader<>)));
  62. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IChannel), typeof(ChannelTypeReader<>)));
  63. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IRole), typeof(RoleTypeReader<>)));
  64. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IUser), typeof(UserTypeReader<>)));
  65. _entityTypeReaders = entityTypeReaders.ToImmutable();
  66. }
  67. //Modules
  68. public async Task<ModuleInfo> CreateModuleAsync(string primaryAlias, Action<ModuleBuilder> buildFunc)
  69. {
  70. await _moduleLock.WaitAsync().ConfigureAwait(false);
  71. try
  72. {
  73. var builder = new ModuleBuilder(this, null, primaryAlias);
  74. buildFunc(builder);
  75. var module = builder.Build(this);
  76. return LoadModuleInternal(module);
  77. }
  78. finally
  79. {
  80. _moduleLock.Release();
  81. }
  82. }
  83. public Task<ModuleInfo> AddModuleAsync<T>() => AddModuleAsync(typeof(T));
  84. public async Task<ModuleInfo> AddModuleAsync(Type type)
  85. {
  86. await _moduleLock.WaitAsync().ConfigureAwait(false);
  87. try
  88. {
  89. var typeInfo = type.GetTypeInfo();
  90. if (_typedModuleDefs.ContainsKey(type))
  91. throw new ArgumentException($"This module has already been added.");
  92. var module = (await ModuleClassBuilder.BuildAsync(this, typeInfo).ConfigureAwait(false)).FirstOrDefault();
  93. if (module.Value == default(ModuleInfo))
  94. throw new InvalidOperationException($"Could not build the module {type.FullName}, did you pass an invalid type?");
  95. _typedModuleDefs[module.Key] = module.Value;
  96. return LoadModuleInternal(module.Value);
  97. }
  98. finally
  99. {
  100. _moduleLock.Release();
  101. }
  102. }
  103. public async Task<IEnumerable<ModuleInfo>> AddModulesAsync(Assembly assembly)
  104. {
  105. await _moduleLock.WaitAsync().ConfigureAwait(false);
  106. try
  107. {
  108. var types = await ModuleClassBuilder.SearchAsync(assembly, this).ConfigureAwait(false);
  109. var moduleDefs = await ModuleClassBuilder.BuildAsync(types, this).ConfigureAwait(false);
  110. foreach (var info in moduleDefs)
  111. {
  112. _typedModuleDefs[info.Key] = info.Value;
  113. LoadModuleInternal(info.Value);
  114. }
  115. return moduleDefs.Select(x => x.Value).ToImmutableArray();
  116. }
  117. finally
  118. {
  119. _moduleLock.Release();
  120. }
  121. }
  122. private ModuleInfo LoadModuleInternal(ModuleInfo module)
  123. {
  124. _moduleDefs.Add(module);
  125. foreach (var command in module.Commands)
  126. _map.AddCommand(command);
  127. foreach (var submodule in module.Submodules)
  128. LoadModuleInternal(submodule);
  129. return module;
  130. }
  131. public async Task<bool> RemoveModuleAsync(ModuleInfo module)
  132. {
  133. await _moduleLock.WaitAsync().ConfigureAwait(false);
  134. try
  135. {
  136. return RemoveModuleInternal(module);
  137. }
  138. finally
  139. {
  140. _moduleLock.Release();
  141. }
  142. }
  143. public Task<bool> RemoveModuleAsync<T>() => RemoveModuleAsync(typeof(T));
  144. public async Task<bool> RemoveModuleAsync(Type type)
  145. {
  146. await _moduleLock.WaitAsync().ConfigureAwait(false);
  147. try
  148. {
  149. if (!_typedModuleDefs.TryRemove(type, out var module))
  150. return false;
  151. return RemoveModuleInternal(module);
  152. }
  153. finally
  154. {
  155. _moduleLock.Release();
  156. }
  157. }
  158. private bool RemoveModuleInternal(ModuleInfo module)
  159. {
  160. if (!_moduleDefs.Remove(module))
  161. return false;
  162. foreach (var cmd in module.Commands)
  163. _map.RemoveCommand(cmd);
  164. foreach (var submodule in module.Submodules)
  165. {
  166. RemoveModuleInternal(submodule);
  167. }
  168. return true;
  169. }
  170. //Type Readers
  171. /// <summary>
  172. /// Adds a custom <see cref="TypeReader"/> to this <see cref="CommandService"/> for the supplied object type.
  173. /// If <typeparamref name="T"/> is a <see cref="ValueType"/>, a <see cref="NullableTypeReader{T}"/> will also be added.
  174. /// </summary>
  175. /// <typeparam name="T">The object type to be read by the <see cref="TypeReader"/>.</typeparam>
  176. /// <param name="reader">An instance of the <see cref="TypeReader"/> to be added.</param>
  177. public void AddTypeReader<T>(TypeReader reader)
  178. => AddTypeReader(typeof(T), reader);
  179. /// <summary>
  180. /// Adds a custom <see cref="TypeReader"/> to this <see cref="CommandService"/> for the supplied object type.
  181. /// If <paramref name="type"/> is a <see cref="ValueType"/>, a <see cref="NullableTypeReader{T}"/> for the value type will also be added.
  182. /// </summary>
  183. /// <param name="type">A <see cref="Type"/> instance for the type to be read.</param>
  184. /// <param name="reader">An instance of the <see cref="TypeReader"/> to be added.</param>
  185. public void AddTypeReader(Type type, TypeReader reader)
  186. {
  187. var readers = _typeReaders.GetOrAdd(type, x => new ConcurrentDictionary<Type, TypeReader>());
  188. readers[reader.GetType()] = reader;
  189. if (type.GetTypeInfo().IsValueType)
  190. AddNullableTypeReader(type, reader);
  191. }
  192. internal void AddNullableTypeReader(Type valueType, TypeReader valueTypeReader)
  193. {
  194. var readers = _typeReaders.GetOrAdd(typeof(Nullable<>).MakeGenericType(valueType), x => new ConcurrentDictionary<Type, TypeReader>());
  195. var nullableReader = NullableTypeReader.Create(valueType, valueTypeReader);
  196. readers[nullableReader.GetType()] = nullableReader;
  197. }
  198. internal IDictionary<Type, TypeReader> GetTypeReaders(Type type)
  199. {
  200. if (_typeReaders.TryGetValue(type, out var definedTypeReaders))
  201. return definedTypeReaders;
  202. return null;
  203. }
  204. internal TypeReader GetDefaultTypeReader(Type type)
  205. {
  206. if (_defaultTypeReaders.TryGetValue(type, out var reader))
  207. return reader;
  208. var typeInfo = type.GetTypeInfo();
  209. //Is this an enum?
  210. if (typeInfo.IsEnum)
  211. {
  212. reader = EnumTypeReader.GetReader(type);
  213. _defaultTypeReaders[type] = reader;
  214. return reader;
  215. }
  216. //Is this an entity?
  217. for (int i = 0; i < _entityTypeReaders.Count; i++)
  218. {
  219. if (type == _entityTypeReaders[i].Item1 || typeInfo.ImplementedInterfaces.Contains(_entityTypeReaders[i].Item1))
  220. {
  221. reader = Activator.CreateInstance(_entityTypeReaders[i].Item2.MakeGenericType(type)) as TypeReader;
  222. _defaultTypeReaders[type] = reader;
  223. return reader;
  224. }
  225. }
  226. return null;
  227. }
  228. //Execution
  229. public SearchResult Search(ICommandContext context, int argPos)
  230. => Search(context, context.Message.Content.Substring(argPos));
  231. public SearchResult Search(ICommandContext context, string input)
  232. {
  233. string searchInput = _caseSensitive ? input : input.ToLowerInvariant();
  234. var matches = _map.GetCommands(searchInput).OrderByDescending(x => x.Command.Priority).ToImmutableArray();
  235. if (matches.Length > 0)
  236. return SearchResult.FromSuccess(input, matches);
  237. else
  238. return SearchResult.FromError(CommandError.UnknownCommand, "Unknown command.");
  239. }
  240. public Task<IResult> ExecuteAsync(ICommandContext context, int argPos, IServiceProvider services = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
  241. => ExecuteAsync(context, context.Message.Content.Substring(argPos), services, multiMatchHandling);
  242. public async Task<IResult> ExecuteAsync(ICommandContext context, string input, IServiceProvider services = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
  243. {
  244. services = services ?? EmptyServiceProvider.Instance;
  245. var searchResult = Search(context, input);
  246. if (!searchResult.IsSuccess)
  247. return searchResult;
  248. var commands = searchResult.Commands;
  249. var preconditionResults = new Dictionary<CommandMatch, PreconditionResult>();
  250. foreach (var match in commands)
  251. {
  252. preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services).ConfigureAwait(false);
  253. }
  254. var successfulPreconditions = preconditionResults
  255. .Where(x => x.Value.IsSuccess)
  256. .ToArray();
  257. if (successfulPreconditions.Length == 0)
  258. {
  259. //All preconditions failed, return the one from the highest priority command
  260. var bestCandidate = preconditionResults
  261. .OrderByDescending(x => x.Key.Command.Priority)
  262. .FirstOrDefault(x => !x.Value.IsSuccess);
  263. return bestCandidate.Value;
  264. }
  265. //If we get this far, at least one precondition was successful.
  266. var parseResultsDict = new Dictionary<CommandMatch, ParseResult>();
  267. foreach (var pair in successfulPreconditions)
  268. {
  269. var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services).ConfigureAwait(false);
  270. if (parseResult.Error == CommandError.MultipleMatches)
  271. {
  272. IReadOnlyList<TypeReaderValue> argList, paramList;
  273. switch (multiMatchHandling)
  274. {
  275. case MultiMatchHandling.Best:
  276. argList = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
  277. paramList = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
  278. parseResult = ParseResult.FromSuccess(argList, paramList);
  279. break;
  280. }
  281. }
  282. parseResultsDict[pair.Key] = parseResult;
  283. }
  284. // Calculates the 'score' of a command given a parse result
  285. float CalculateScore(CommandMatch match, ParseResult parseResult)
  286. {
  287. float argValuesScore = 0, paramValuesScore = 0;
  288. if (match.Command.Parameters.Count > 0)
  289. {
  290. var argValuesSum = parseResult.ArgValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
  291. var paramValuesSum = parseResult.ParamValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
  292. argValuesScore = argValuesSum / match.Command.Parameters.Count;
  293. paramValuesScore = paramValuesSum / match.Command.Parameters.Count;
  294. }
  295. var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
  296. return match.Command.Priority + totalArgsScore * 0.99f;
  297. }
  298. //Order the parse results by their score so that we choose the most likely result to execute
  299. var parseResults = parseResultsDict
  300. .OrderByDescending(x => CalculateScore(x.Key, x.Value));
  301. var successfulParses = parseResults
  302. .Where(x => x.Value.IsSuccess)
  303. .ToArray();
  304. if (successfulParses.Length == 0)
  305. {
  306. //All parses failed, return the one from the highest priority command, using score as a tie breaker
  307. var bestMatch = parseResults
  308. .FirstOrDefault(x => !x.Value.IsSuccess);
  309. return bestMatch.Value;
  310. }
  311. //If we get this far, at least one parse was successful. Execute the most likely overload.
  312. var chosenOverload = successfulParses[0];
  313. return await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
  314. }
  315. }
  316. }