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

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