DocSpace-buildtools/common/services/ASC.TelegramService/Core/Core.cs

176 lines
6.3 KiB
C#
Raw Normal View History

2020-09-24 14:30:27 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2020
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
2022-02-17 11:16:52 +00:00
namespace ASC.TelegramService.Core;
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
public class TelegramCommand
{
public string CommandName { get; private set; }
public string[] Args { get; private set; }
public Message Message { get; private set; }
public User User { get { return Message.From; } }
public Chat Chat { get { return Message.Chat; } }
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
public TelegramCommand(Message msg, string cmdName, string[] args = null)
{
Message = msg;
CommandName = cmdName;
Args = args;
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
}
2020-10-19 15:53:15 +00:00
2022-02-17 11:16:52 +00:00
[Singletone]
public class CommandModule
{
private readonly Regex _cmdReg = new Regex(@"^\/([^\s]+)\s?(.*)");
private readonly Regex _argsReg = new Regex(@"[^""\s]\S*|"".+?""");
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
private readonly Dictionary<string, MethodInfo> _commands = new Dictionary<string, MethodInfo>();
private readonly Dictionary<string, Type> _contexts = new Dictionary<string, Type>();
private readonly Dictionary<Type, ParamParser> _parsers = new Dictionary<Type, ParamParser>();
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILog _log;
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
public CommandModule(IOptionsMonitor<ILog> options, IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
_log = options.CurrentValue;
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
var assembly = Assembly.GetExecutingAssembly();
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
foreach (var t in assembly.GetExportedTypes())
{
if (t.IsAbstract) continue;
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
if (t.IsSubclassOf(typeof(CommandContext)))
{
foreach (var method in t.GetRuntimeMethods())
2020-09-24 14:30:27 +00:00
{
2022-02-17 11:16:52 +00:00
if (method.IsPublic && Attribute.IsDefined(method, typeof(CommandAttribute)))
2020-09-24 14:30:27 +00:00
{
2022-02-17 11:16:52 +00:00
var attr = method.GetCustomAttribute<CommandAttribute>();
_commands.Add(attr.Name, method);
_contexts.Add(attr.Name, t);
2020-09-24 14:30:27 +00:00
}
}
2022-02-17 11:16:52 +00:00
}
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
if (t.IsSubclassOf(typeof(ParamParser)) && Attribute.IsDefined(t, typeof(ParamParserAttribute)))
{
_parsers.Add(t.GetCustomAttribute<ParamParserAttribute>().Type, (ParamParser)Activator.CreateInstance(t));
2020-09-24 14:30:27 +00:00
}
}
2022-02-17 11:16:52 +00:00
}
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
private TelegramCommand ParseCommand(Message msg)
{
var reg = _cmdReg.Match(msg.Text);
var args = _argsReg.Matches(reg.Groups[2].Value);
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
return new TelegramCommand(msg, reg.Groups[1].Value.ToLowerInvariant(), args.Count > 0 ? args.Select(a => a.Value).ToArray() : null);
}
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
private object[] ParseParams(MethodInfo cmd, string[] args)
{
var parsedParams = new List<object>();
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
var cmdArgs = cmd.GetParameters();
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
if (cmdArgs.Length > 0 && args == null || cmdArgs.Length != args.Length) throw new Exception("Wrong parameters count");
for (var i = 0; i < cmdArgs.Length; i++)
{
var type = cmdArgs[i].ParameterType;
var arg = args[i];
if (type == typeof(string))
2020-09-24 14:30:27 +00:00
{
2022-02-17 11:16:52 +00:00
parsedParams.Add(arg);
continue;
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
if (!_parsers.ContainsKey(type)) throw new Exception(string.Format("No parser found for type '{0}'", type));
parsedParams.Add(_parsers[type].FromString(arg));
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
return parsedParams.ToArray();
}
public async Task HandleCommand(Message msg, TelegramBotClient client, int tenantId)
{
try
2020-09-24 14:30:27 +00:00
{
2022-02-17 11:16:52 +00:00
var cmd = ParseCommand(msg);
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
if (!_commands.ContainsKey(cmd.CommandName)) throw new Exception($"No handler found for command '{cmd.CommandName}'");
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
var command = _commands[cmd.CommandName];
var context = (CommandContext)_scopeFactory.CreateScope().ServiceProvider.GetService(_contexts[cmd.CommandName]);
var param = ParseParams(command, cmd.Args);
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
context.Context = cmd;
context.Client = client;
context.TenantId = tenantId;
await Task.FromResult(command.Invoke(context, param));
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
catch (Exception ex)
2020-09-24 14:30:27 +00:00
{
2022-02-17 11:16:52 +00:00
_log.DebugFormat("Couldn't handle ({0}) message ({1})", msg.Text, ex.Message);
2020-09-24 14:30:27 +00:00
}
}
2022-02-17 11:16:52 +00:00
}
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
public abstract class CommandContext
{
public ITelegramBotClient Client { get; set; }
public TelegramCommand Context { get; set; }
public int TenantId { get; set; }
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
protected async Task ReplyAsync(string message)
{
await Client.SendTextMessageAsync(Context.Chat, message);
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
}
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
public abstract class ParamParser
{
protected Type type;
2020-09-24 14:30:27 +00:00
2022-02-17 11:16:52 +00:00
protected ParamParser(Type type)
{
this.type = type;
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
public abstract object FromString(string arg);
public abstract string ToString(object arg);
2020-09-24 14:30:27 +00:00
}
2022-02-17 11:16:52 +00:00
public abstract class ParamParser<T> : ParamParser
{
protected ParamParser() : base(typeof(T)) { }
public override abstract object FromString(string arg);
public override abstract string ToString(object arg);
}