using AsbCloudApp.Services; using AsbCloudWebApi.SignalR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers.SAUB { [Route("api/[controller]")] [ApiController] public abstract class TelemetryInstantDataController : ControllerBase { private readonly ITelemetryService telemetryService; private readonly IWellService wellService; private readonly IHubContext telemetryHubContext; private readonly InstantDataRepository repository; protected abstract string SirnalRMethodGetDataName { get; } public TelemetryInstantDataController( ITelemetryService telemetryService, IWellService wellService, IHubContext telemetryHubContext, InstantDataRepository repository) { this.telemetryService = telemetryService; this.wellService = wellService; this.telemetryHubContext = telemetryHubContext; this.repository = repository; } /// /// Принимает данные от панели /// /// /// /// [HttpPost] [Route("{uid}")] [AllowAnonymous] public virtual IActionResult PostData( string uid, [FromBody] TDto dto) { if (dto is null) return BadRequest("Dto shouldn't be null"); var idTelemetry = telemetryService.GetOrCreateTelemetryIdByUid(uid); var typedStore = repository.GetOrAdd(idTelemetry, (id) => new System.Collections.Concurrent.ConcurrentDictionary()); var typeDto = typeof(TDto); typedStore.AddOrUpdate(typeDto, dto, (_, _) => dto); var idWell = telemetryService.GetIdWellByTelemetryUid(uid); if (idWell is not null) _ = Task.Run(async () => { var clients = telemetryHubContext.Clients.Group($"well_{idWell}"); await clients.SendAsync(SirnalRMethodGetDataName, dto); }, CancellationToken.None); return Ok(); } /// /// Выдает данные по скважине /// /// /// /// [HttpGet("{idWell}")] //[Permission] public virtual async Task> GetDataAsync( int idWell, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token).ConfigureAwait(false); if (!isCompanyOwnsWell) return Forbid(); int? idTelemetry = telemetryService.GetOrDefaultIdTelemetryByIdWell(idWell); if (idTelemetry is null) return NoContent(); var typedStore = repository.GetValueOrDefault((int)idTelemetry, null); if (typedStore is null) return NoContent(); var typeDto = typeof(TDto); var dto = typedStore.GetValueOrDefault(typeDto); return Ok(dto); } } }