RPCCommandHandler.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using GenHTTP.Api.Content.Authentication;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using Microsoft.Exchange.WebServices.Data;
  5. using NPOI.SS.Formula.Functions;
  6. namespace InABox.Rpc
  7. {
  8. public abstract class RpcCommandHandler<TSender, TCommand, TParameters, TResult> : IRpcCommandHandler
  9. where TSender : class
  10. where TCommand : IRpcCommand<TParameters, TResult>
  11. where TParameters : IRpcCommandParameters, new()
  12. where TResult : IRpcCommandResult
  13. {
  14. public TSender Sender { get; }
  15. private static readonly bool IsLogCommand = typeof(TCommand).IsAssignableTo(typeof(IRpcLogCommand));
  16. public RpcCommandHandler(TSender sender)
  17. {
  18. Sender = sender ?? throw new ArgumentNullException(nameof(sender));
  19. }
  20. protected abstract TResult Execute(IRpcSession session, TParameters parameters);
  21. public byte[] Execute(IRpcSession session, byte[] payload)
  22. {
  23. var start = DateTime.Now;
  24. var parameters = Serialization.ReadBinary<TParameters>(payload, BinarySerializationSettings.Latest);
  25. if (IsLogCommand)
  26. Logger.Send(LogType.Information, session.UserID, $"[{session.Platform} {session.Version}] {parameters.ShortDescription()}: {parameters.FullDescription()}");
  27. try
  28. {
  29. var result = Execute(session, parameters);
  30. if (IsLogCommand)
  31. {
  32. Logger.Send(LogType.Information, session.UserID,
  33. string.Format(
  34. "[{0} {1}] [{2:D8}] {3} Complete: {4}",
  35. session.Platform, session.Version,
  36. (int)DateTime.Now.Subtract(start).TotalMilliseconds,
  37. parameters.ShortDescription(),
  38. result.FullDescription()
  39. )
  40. );
  41. }
  42. return Serialization.WriteBinary(result, BinarySerializationSettings.Latest);
  43. }
  44. catch (RpcException)
  45. {
  46. throw;
  47. }
  48. catch (Exception e)
  49. {
  50. Logger.Send(LogType.Information, session.UserID, string.Format("[{0} {1}] [{2:D8}] {3} failed: {4}\n\n{5}",
  51. session.Platform,
  52. session.Version,
  53. (int)DateTime.Now.Subtract(start).TotalMilliseconds,
  54. parameters.ShortDescription(),
  55. e.Message,
  56. e.StackTrace));
  57. throw new RpcException(e.Message, RpcError.SERVERERROR);
  58. }
  59. }
  60. }
  61. }