add support for REST-ful API building
- allow parameters within url - allow different methods other then just POST -> still needs to be tested!
This commit is contained in:
@@ -1,14 +1,20 @@
|
||||
using Castle.Core.Logging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Pilz.Extensions.Reflection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
using static Pilz.Net.Api.IApiServer;
|
||||
|
||||
namespace Pilz.Net.Api;
|
||||
|
||||
public class ApiServer(string apiUrl) : IApiServer
|
||||
{
|
||||
protected readonly Dictionary<string, Delegate> handlers = [];
|
||||
protected readonly List<PrivateMessageHandler> handlers = [];
|
||||
protected readonly Dictionary<Type, IApiMessageSerializer> serializers = [];
|
||||
protected readonly HttpListener httpListener = new();
|
||||
|
||||
@@ -16,6 +22,10 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
public event OnCheckContextEventHandler? OnCheckContext;
|
||||
public event OnCheckContextEventHandler? OnCheckContextCompleted;
|
||||
|
||||
protected record PrivateParameterInfo(string Name, int Index);
|
||||
|
||||
protected record PrivateMessageHandler(string Url, bool UseRegEx, Delegate Handler, PrivateParameterInfo[] Parameters, ApiMessageHandlerAttribute Attribute);
|
||||
|
||||
protected record PrivateApiResult(ApiResult Original, string? ResultJson);
|
||||
|
||||
public string ApiUrl { get; } = apiUrl;
|
||||
@@ -72,10 +82,33 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
return;
|
||||
}
|
||||
|
||||
// Resolves parameters
|
||||
var url = attribute.Route;
|
||||
var useRegEx = false;
|
||||
var nextBreacket = url.IndexOf('{');
|
||||
var parameters = new List<PrivateParameterInfo>();
|
||||
while (nextBreacket != -1)
|
||||
{
|
||||
var endBreacket = url.IndexOf('}', nextBreacket + 1);
|
||||
if (endBreacket == -1)
|
||||
{
|
||||
var name = url.Substring(nextBreacket + 1, endBreacket - nextBreacket - 1);
|
||||
const string regex = "[A-Za-z0-9%]+";
|
||||
url = url.Replace(url.Substring(nextBreacket, endBreacket + 1), regex);
|
||||
|
||||
var index = url.Substring(0, nextBreacket + 1).Split('/').Length;
|
||||
parameters.Add(new(name, index));
|
||||
|
||||
useRegEx = true;
|
||||
nextBreacket = url.IndexOf('{', endBreacket + 1);
|
||||
}
|
||||
}
|
||||
if (useRegEx)
|
||||
url = url.Replace(".", "\\."); // Escape special characters
|
||||
|
||||
// Add handler
|
||||
var fullUrl = attribute.Route;
|
||||
Log.InfoFormat("Added handler for {0}", fullUrl);
|
||||
handlers.Add(fullUrl, handler);
|
||||
Log.InfoFormat("Added handler for {0}", attribute.Route);
|
||||
handlers.Add(new(url, useRegEx, handler, [.. parameters], attribute));
|
||||
}
|
||||
|
||||
protected void Receive()
|
||||
@@ -143,16 +176,6 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
context.Response.OutputStream.Close();
|
||||
}
|
||||
|
||||
Log.Debug("Sanity checks");
|
||||
if (context.Request.HttpMethod != HttpMethod.Post.Method
|
||||
|| context.Request.ContentType is not string contentType
|
||||
|| !contentType.Contains("application/json"))
|
||||
{
|
||||
Log.Info("Request has no json content");
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse url
|
||||
Log.Debug("Parse url");
|
||||
var path = context.Request.Url?.PathAndQuery.Replace(ApiUrl, string.Empty);
|
||||
@@ -163,25 +186,51 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
return;
|
||||
}
|
||||
|
||||
// Read input content
|
||||
Log.Debug("Read input content");
|
||||
string? contentJson;
|
||||
if (context.Request.ContentLength64 > 0)
|
||||
// Find handler
|
||||
Log.Debug("Find handler");
|
||||
if (!TryGetHandler(path, context.Request.HttpMethod, out var handler))
|
||||
{
|
||||
using StreamReader input = new(context.Request.InputStream);
|
||||
contentJson = input.ReadToEnd();
|
||||
Log.Info("Request handler couldn't be found");
|
||||
close();
|
||||
return;
|
||||
}
|
||||
else
|
||||
contentJson = null;
|
||||
|
||||
// Get auth key
|
||||
Log.Debug("Get auth key");
|
||||
if (context.Request.Headers.Get("API-AUTH-KEY") is not string authKey)
|
||||
authKey = null!;
|
||||
|
||||
// Read input content
|
||||
Log.Debug("Read input content");
|
||||
string? contentJson;
|
||||
if (context.Request.ContentType is string contentType
|
||||
&& contentType.Contains("application/json")
|
||||
&& context.Request.ContentLength64 > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
using StreamReader input = new(context.Request.InputStream);
|
||||
contentJson = input.ReadToEnd();
|
||||
}
|
||||
catch (OutOfMemoryException)
|
||||
{
|
||||
Log.Error("Error reading remote data due to missing memory");
|
||||
close();
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("Error reading remote data", ex);
|
||||
close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
contentJson = null;
|
||||
|
||||
// Handle message
|
||||
Log.Debug("Handle mssage");
|
||||
if (HandleMessage(path, contentJson, authKey) is not PrivateApiResult result)
|
||||
if (HandleMessage(path, context.Request.HttpMethod, handler, contentJson, authKey) is not PrivateApiResult result)
|
||||
{
|
||||
Log.Warn("Request couldn't be handled");
|
||||
close();
|
||||
@@ -206,28 +255,22 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
close();
|
||||
}
|
||||
|
||||
protected virtual PrivateApiResult? HandleMessage(string url, string? json, string? authKey)
|
||||
protected virtual PrivateApiResult? HandleMessage(string url, string method, PrivateMessageHandler handler, string? json, string? authKey)
|
||||
{
|
||||
// Get handler
|
||||
Log.Debug("Find handler");
|
||||
if (!handlers.TryGetValue(url, out var handler)
|
||||
|| handler.Method.GetCustomAttribute<ApiMessageHandlerAttribute>() is not ApiMessageHandlerAttribute attribute)
|
||||
return null;
|
||||
|
||||
// Check authentication
|
||||
Log.Debug("Check authentication");
|
||||
var isAuthenticated = false;
|
||||
if (!string.IsNullOrWhiteSpace(authKey) && DecodeAuthKey(authKey) is string authKeyDecoded)
|
||||
isAuthenticated = CheckAuthentication(authKeyDecoded, handler);
|
||||
isAuthenticated = CheckAuthentication(authKeyDecoded, handler.Handler);
|
||||
else
|
||||
authKeyDecoded = null!;
|
||||
if (attribute.RequiesAuth && !isAuthenticated)
|
||||
if (handler.Attribute.RequiesAuth && !isAuthenticated)
|
||||
return new(ApiResult.Unauthorized(), null);
|
||||
|
||||
// Get required infos
|
||||
Log.Debug("Identify message parameter type and serializer");
|
||||
var targetType = handler.Method.GetParameters().FirstOrDefault(p => p.ParameterType.IsAssignableTo(typeof(ApiMessage)))?.ParameterType;
|
||||
var serializer = GetSerializer(attribute.Serializer);
|
||||
var targetType = handler.Handler.Method.GetParameters().FirstOrDefault(p => p.ParameterType.IsAssignableTo(typeof(ApiMessage)))?.ParameterType;
|
||||
var serializer = GetSerializer(handler.Attribute.Serializer);
|
||||
|
||||
// Deserialize
|
||||
Log.Debug("Deserialize message");
|
||||
@@ -239,8 +282,8 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
|
||||
// Invoke handler
|
||||
Log.Debug("Invoke handler");
|
||||
var parameters = BuildParameters(handler, () => message, () => new(message, isAuthenticated, authKeyDecoded));
|
||||
if (handler.DynamicInvoke(parameters) is not ApiResult result)
|
||||
var parameters = BuildParameters(url, handler, () => message, () => new(message, isAuthenticated, authKeyDecoded, url, method));
|
||||
if (handler.Handler.DynamicInvoke(parameters) is not ApiResult result)
|
||||
return new(ApiResult.InternalServerError(), null);
|
||||
|
||||
// Return result without message
|
||||
@@ -258,9 +301,25 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
return new(result, resultStr);
|
||||
}
|
||||
|
||||
protected virtual object?[]? BuildParameters(Delegate handler, Func<ApiMessage?> getMessage, Func<ApiRequestInfo> getRequestInfo)
|
||||
protected virtual bool TryGetHandler(string url, string method, [NotNullWhen(true)] out PrivateMessageHandler? handler)
|
||||
{
|
||||
var infos = handler.Method.GetParameters();
|
||||
handler = handlers.FirstOrDefault(handler =>
|
||||
{
|
||||
if (!handler.Attribute.Methods.Contains(method))
|
||||
return false;
|
||||
|
||||
if (handler.UseRegEx)
|
||||
return Regex.IsMatch(url, handler.Url, RegexOptions.IgnoreCase);
|
||||
|
||||
return handler.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase);
|
||||
});
|
||||
|
||||
return handler != null;
|
||||
}
|
||||
|
||||
protected virtual object?[]? BuildParameters(string url, PrivateMessageHandler handler, Func<ApiMessage?> getMessage, Func<ApiRequestInfo> getRequestInfo)
|
||||
{
|
||||
var infos = handler.Handler.Method.GetParameters();
|
||||
var objs = new List<object?>();
|
||||
|
||||
foreach (var info in infos)
|
||||
@@ -269,6 +328,9 @@ public class ApiServer(string apiUrl) : IApiServer
|
||||
objs.Add(getMessage());
|
||||
else if (info.ParameterType.IsAssignableTo(typeof(ApiRequestInfo)))
|
||||
objs.Add(getRequestInfo());
|
||||
else if (handler.Parameters.FirstOrDefault(p => p.Name.Equals(info.Name, StringComparison.InvariantCultureIgnoreCase)) is PrivateParameterInfo parameterInfo
|
||||
&& url.Split('/').ElementAtOrDefault(parameterInfo.Index) is string parameterValue)
|
||||
objs.Add(Convert.ChangeType(HttpUtility.UrlDecode(parameterValue), info.ParameterType)); // or Uri.UnescapeDataString(); maybe run this line twice?
|
||||
else
|
||||
objs.Add(null);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user