using System.Collections.Concurrent; using System.Reflection; using AyCode.Core.Extensions; using AyCode.Core.Loggers; using AyCode.Services.SignalRs; using Microsoft.AspNetCore.SignalR; using TIAM.Database.DataLayers.Admins; using MessagePack.Resolvers; using AyCode.Services.Server.SignalRs; using DevExpress.Utils.Filtering; using TIAM.Entities.Transfers; using TIAM.Services; using TIAMWebApp.Server.Controllers; using TIAM.Entities.ServiceProviders; using System.Runtime.CompilerServices; using MessagePack; using System.Security.Cryptography.Xml; using DevExpress.XtraPrinting.Native.WebClientUIControl; namespace TIAMWebApp.Server.Services; public static class ExtensionMethods { public static object? InvokeMethod(this MethodInfo methodInfo, object obj, params object[]? parameters) { if (methodInfo.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) is AsyncStateMachineAttribute isTaks) { dynamic awaitable = methodInfo.Invoke(obj, parameters)!; return awaitable.GetAwaiter().GetResult(); } return methodInfo.Invoke(obj, parameters); } } public enum MethodParamType : byte { None = 0, Id = 5, Object = 10 } [AttributeUsage(AttributeTargets.Method)] public class SignalRAttribute(int messageTag, MethodParamType methodParamType, Type paramType = null) : Attribute { public int MessageTag { get; init; } = messageTag; public MethodParamType MethodParamType { get; init; } = methodParamType; public Type ParamType { get; init; } = paramType; } public class DevAdminSignalRHub : Hub, IAcSignalRHubServer { private readonly ConcurrentDictionary> _methodsByMessageTag = new(); private readonly TIAM.Core.Loggers.Logger _logger; private readonly AdminDal _adminDal; private readonly ServiceProviderAPIController _serviceProviderApiController; private readonly TransferDataAPIController _transferDataApiController; public DevAdminSignalRHub(AdminDal adminDal, ServiceProviderAPIController serviceProviderApiController, TransferDataAPIController transferDataApiController, IEnumerable logWriters) { _adminDal = adminDal; _serviceProviderApiController = serviceProviderApiController; _transferDataApiController = transferDataApiController; _logger = new(logWriters.ToArray()); var methods = typeof(ServiceProviderAPIController).GetMethods().Where(x => x.GetCustomAttributes(typeof(SignalRAttribute), false).Length > 0); _methodsByMessageTag[serviceProviderApiController] = new(); foreach (var methodInfo in methods) { var atr = methodInfo.GetCustomAttribute(typeof(SignalRAttribute)) as SignalRAttribute; _methodsByMessageTag[serviceProviderApiController][atr.MessageTag] = methodInfo; } methods = typeof(TransferDataAPIController).GetMethods().Where(x => x.GetCustomAttributes(typeof(SignalRAttribute), false).Length > 0); _methodsByMessageTag[transferDataApiController] = new(); foreach (var methodInfo in methods) { var atr = methodInfo.GetCustomAttribute(typeof(SignalRAttribute)) as SignalRAttribute; _methodsByMessageTag[transferDataApiController][atr.MessageTag] = methodInfo; } } // https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-3.1#strongly-typed-hubs public override async Task OnConnectedAsync() { _logger.Debug($"Server OnConnectedAsync; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}"); //await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnConnectedAsync(); //Clients.Caller.ConnectionId = Context.ConnectionId; //Clients.Caller.UserIdentifier = Context.UserIdentifier; } public override async Task OnDisconnectedAsync(Exception? exception) { _logger.ErrorConditional($"Server OnDisconnectedAsync; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}", exception); //await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnDisconnectedAsync(exception); } //public async Task OnRequestMessage(int messageTag, int requestId) //{ // _logger.Info($"Server OnRequestMessage; {nameof(messageTag)}: {messageTag}; {nameof(requestId)}: {requestId}; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}"); // if (messageTag == SignalRTags.GetTransfersAsync) // await ResponseToCaller(SignalRTags.PostTransfersAsync, await adminDal.GetTransfersJsonAsync(), requestId); //} public async Task OnReceiveMessage(int messageTag, byte[]? message, int? requestId) { var logText = $"Server OnReceiveMessage; {nameof(messageTag)}: {messageTag}; {nameof(requestId)}: {requestId}; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}"; if (message is { Length: 0 }) _logger.Warning($"message.Length == 0! {logText}"); else _logger.Info(logText); try { foreach (var methodsByDeclaringObject in _methodsByMessageTag) { if (methodsByDeclaringObject.Value.TryGetValue(messageTag, out var methodInfo)) { var atr = methodInfo.GetCustomAttribute(typeof(SignalRAttribute)) as SignalRAttribute; object[]? param = null; if (atr.MethodParamType != MethodParamType.None) { param = new object[1]; if (atr.MethodParamType == MethodParamType.Id) { param[0] = message!.MessagePackTo().Id; } else { var msg = message!.MessagePackTo>(MessagePackSerializerOptions.Standard); param[0] = msg.PostDataJson.JsonTo(atr.ParamType)!; } } await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success, methodInfo.InvokeMethod(methodsByDeclaringObject.Key, param)), requestId); return; } } switch (messageTag) { case SignalRTags.RemoveCompanyAsync: var deleteCompany = message!.MessagePackTo>().PostData; await _adminDal.RemoveCompanyAsync(deleteCompany.Id); await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success), requestId); return; //case SignalRTags.GetTransfersAsync: // await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success, await _transferDataApiController.GetTransfers()), requestId); // return; //case SignalRTags.GetPropertiesByOwnerIdAsync: // var ownerId = message!.MessagePackTo().Id; // await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success, await _serviceProviderApiController.GetServiceProvidersByOwnerId(ownerId)), requestId); // return; //case SignalRTags.UpdateTransferAsync: // var transfer = message!.MessagePackTo>().PostData; // await _transferDataApiController.UpdateTransfer(transfer); // await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success, transfer), requestId); // return; //case SignalRTags.GetCompaniesAsync: // await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success, await _serviceProviderApiController.GetServiceProviders()), requestId); // return; //case SignalRTags.UpdateCompanyAsync: // var updateCompany = message!.MessagePackTo>().PostData; // await _serviceProviderApiController.UpdateServiceProvider(updateCompany); // await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Success, updateCompany), requestId); // return; default: _logger.Error($"Server OnReceiveMessage; messageTag not found! messageTag: {messageTag}"); break; } } catch (Exception ex) { _logger.Error($"Server OnReceiveMessage; {ex.Message}", ex); } await ResponseToCaller(messageTag, new SignalResponseJsonMessage(SignalResponseStatus.Error), requestId); } protected async Task ResponseToCaller(int messageTag, ISignalRMessage message, int? requestId) => await SendMessageToClient(Clients.Caller, messageTag, message, requestId); protected async Task SendMessageToClient(ISignalRHubItemServer sendTo, int messageTag, ISignalRMessage message, int? requestId = null) { _logger.Info($"Server SendMessageToClient; {nameof(messageTag)}: {messageTag}; {nameof(requestId)}: {requestId}; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}"); await sendTo.OnReceiveMessage(messageTag, message.ToMessagePack(ContractlessStandardResolver.Options), requestId); } //protected void SendRequestToClient(ISignalRHubItemServer sendTo, int messageTag, int requestId) //{ // _logger.Info($"Server SendRequestToClient; {nameof(messageTag)}: {messageTag}; {nameof(requestId)}: {requestId}; ConnectionId: {Context.ConnectionId}; UserIdentifier: {Context.UserIdentifier}"); // sendTo.OnRequestMessage(messageTag, requestId).Forget(); //} public async Task SendMessageToGroup(string groupId, int messageTag, string message) { //await Clients.Group(groupId).Post("", messageTag, message); } }