using System.Text.Json; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.IntegrationEvents; using AsbCloudApp.IntegrationEvents.Events; using AsbCloudInfrastructure.Services; using Microsoft.AspNetCore.SignalR; namespace AsbCloudWebApi.SignalR; public class WellInfoUpdaterHub : Hub, IIntegrationEventHandler { private const string groupTemplate = "system_operation_updater_well_{0}"; private readonly IHubContext hubContext; private readonly WellInfoService wellInfoService; public WellInfoUpdaterHub(IHubContext hubContext, WellInfoService wellInfoService) { this.hubContext = hubContext; this.wellInfoService = wellInfoService; } public async Task OnConnectedAsync(int idWell) { await base.OnConnectedAsync(); await Groups.AddToGroupAsync(Context.ConnectionId, string.Format(groupTemplate, idWell)); await HandleAsync(new WellInfoUpdaterEvent(idWell), CancellationToken.None); } public async Task HandleAsync(WellInfoUpdaterEvent integrationEvent, CancellationToken cancellationToken) { const string method = "well_info_update"; var wellInfo = wellInfoService.FirstOrDefault(w => w.Id == integrationEvent.IdWell); if (wellInfo != null) { var serializedObject = JsonSerializer.Serialize(wellInfo); await hubContext.Clients.Group(string.Format(groupTemplate, integrationEvent.IdWell)) .SendCoreAsync(method, new object[] { serializedObject }, cancellationToken); } } }