DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/SAUB/TelemetryInstantDataController.cs

95 lines
3.2 KiB
C#
Raw Normal View History

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;
2022-04-11 18:00:34 +05:00
namespace AsbCloudWebApi.Controllers.SAUB
{
[Route("api/[controller]")]
[ApiController]
public abstract class TelemetryInstantDataController<TDto> : ControllerBase
{
private readonly ITelemetryService telemetryService;
private readonly IWellService wellService;
private readonly IHubContext<TelemetryHub> telemetryHubContext;
private readonly InstantDataRepository repository;
protected abstract string SirnalRMethodGetDataName { get; }
public TelemetryInstantDataController(
ITelemetryService telemetryService,
IWellService wellService,
IHubContext<TelemetryHub> telemetryHubContext,
InstantDataRepository repository)
{
this.telemetryService = telemetryService;
this.wellService = wellService;
this.telemetryHubContext = telemetryHubContext;
this.repository = repository;
}
[HttpPost]
[Route("{uid}")]
[AllowAnonymous]
public virtual IActionResult PostData(
2022-04-11 18:00:34 +05:00
string uid,
[FromBody] TDto dto)
{
if (dto is null)
return BadRequest("Dto shouldn't be null");
var idTelemetry = telemetryService.GetOrCreateTelemetryIdByUid(uid);
2022-04-11 18:00:34 +05:00
var typedStore = repository.GetOrAdd(idTelemetry, (id) => new System.Collections.Concurrent.ConcurrentDictionary<Type, object>());
var typeDto = typeof(TDto);
2022-04-11 18:00:34 +05:00
typedStore.AddOrUpdate(typeDto, dto, (_, _) => dto);
var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (idWell is not null)
2022-04-11 18:00:34 +05:00
_ = Task.Run(async () =>
{
2022-04-11 18:00:34 +05:00
var clients = telemetryHubContext.Clients.Group($"well_{idWell}");
await clients.SendAsync(SirnalRMethodGetDataName, dto);
}, CancellationToken.None);
return Ok();
}
[HttpGet("{idWell}")]
//[Permission]
public virtual async Task<ActionResult<TDto>> 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.GetIdTelemetryByIdWell(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);
}
}
}