ServerApi.Utility.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. using System.Net;
  2. using System.Net.Http;
  3. using System.Threading.Tasks;
  4. using Robust.Server.ServerStatus;
  5. namespace Content.Server.Administration;
  6. public sealed partial class ServerApi
  7. {
  8. private void RegisterHandler(HttpMethod method, string exactPath, Func<IStatusHandlerContext, Task> handler)
  9. {
  10. _statusHost.AddHandler(async context =>
  11. {
  12. if (context.RequestMethod != method || context.Url.AbsolutePath != exactPath)
  13. return false;
  14. if (!await CheckAccess(context))
  15. return true;
  16. await handler(context);
  17. return true;
  18. });
  19. }
  20. private void RegisterActorHandler(HttpMethod method, string exactPath, Func<IStatusHandlerContext, Actor, Task> handler)
  21. {
  22. RegisterHandler(method, exactPath, async context =>
  23. {
  24. if (await CheckActor(context) is not { } actor)
  25. return;
  26. await handler(context, actor);
  27. });
  28. }
  29. /// <summary>
  30. /// Async helper function which runs a task on the main thread and returns the result.
  31. /// </summary>
  32. private async Task<T> RunOnMainThread<T>(Func<T> func)
  33. {
  34. var taskCompletionSource = new TaskCompletionSource<T>();
  35. _taskManager.RunOnMainThread(() =>
  36. {
  37. try
  38. {
  39. taskCompletionSource.TrySetResult(func());
  40. }
  41. catch (Exception e)
  42. {
  43. taskCompletionSource.TrySetException(e);
  44. }
  45. });
  46. var result = await taskCompletionSource.Task;
  47. return result;
  48. }
  49. /// <summary>
  50. /// Runs an action on the main thread. This does not return any value and is meant to be used for void functions. Use <see cref="RunOnMainThread{T}"/> for functions that return a value.
  51. /// </summary>
  52. private async Task RunOnMainThread(Action action)
  53. {
  54. var taskCompletionSource = new TaskCompletionSource();
  55. _taskManager.RunOnMainThread(() =>
  56. {
  57. try
  58. {
  59. action();
  60. taskCompletionSource.TrySetResult();
  61. }
  62. catch (Exception e)
  63. {
  64. taskCompletionSource.TrySetException(e);
  65. }
  66. });
  67. await taskCompletionSource.Task;
  68. }
  69. private async Task RunOnMainThread(Func<Task> action)
  70. {
  71. var taskCompletionSource = new TaskCompletionSource();
  72. // ReSharper disable once AsyncVoidLambda
  73. _taskManager.RunOnMainThread(async () =>
  74. {
  75. try
  76. {
  77. await action();
  78. taskCompletionSource.TrySetResult();
  79. }
  80. catch (Exception e)
  81. {
  82. taskCompletionSource.TrySetException(e);
  83. }
  84. });
  85. await taskCompletionSource.Task;
  86. }
  87. /// <summary>
  88. /// Helper function to read JSON encoded data from the request body.
  89. /// </summary>
  90. private static async Task<T?> ReadJson<T>(IStatusHandlerContext context) where T : notnull
  91. {
  92. try
  93. {
  94. var json = await context.RequestBodyJsonAsync<T>();
  95. if (json == null)
  96. await RespondBadRequest(context, "Request body is null");
  97. return json;
  98. }
  99. catch (Exception e)
  100. {
  101. await RespondBadRequest(context, "Unable to parse request body", ExceptionData.FromException(e));
  102. return default;
  103. }
  104. }
  105. private static async Task RespondError(
  106. IStatusHandlerContext context,
  107. ErrorCode errorCode,
  108. HttpStatusCode statusCode,
  109. string message,
  110. ExceptionData? exception = null)
  111. {
  112. await context.RespondJsonAsync(new BaseResponse(message, errorCode, exception), statusCode)
  113. .ConfigureAwait(false);
  114. }
  115. private static async Task RespondBadRequest(
  116. IStatusHandlerContext context,
  117. string message,
  118. ExceptionData? exception = null)
  119. {
  120. await RespondError(context, ErrorCode.BadRequest, HttpStatusCode.BadRequest, message, exception)
  121. .ConfigureAwait(false);
  122. }
  123. private static async Task RespondOk(IStatusHandlerContext context)
  124. {
  125. await context.RespondJsonAsync(new BaseResponse("OK"))
  126. .ConfigureAwait(false);
  127. }
  128. private static string FormatLogActor(Actor actor) => $"{actor.Name} ({actor.Guid})";
  129. }