DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/SAUB/TelemetryDataBaseController.cs
2024-08-19 10:01:07 +05:00

203 lines
7.6 KiB
C#

using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Clients;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers.SAUB;
[ApiController]
[Authorize]
[Route("api/[controller]")]
public abstract class TelemetryDataBaseController<TDto> : ControllerBase
where TDto : ITelemetryData
{
protected readonly IWellService wellService;
private readonly ITelemetryService telemetryService;
private readonly ITelemetryDataService<TDto> telemetryDataService;
protected readonly IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext;
public TelemetryDataBaseController(
ITelemetryService telemetryService,
ITelemetryDataService<TDto> telemetryDataService,
IWellService wellService,
IHubContext<TelemetryHub, ITelemetryHubClient> telemetryHubContext)
{
this.telemetryService = telemetryService;
this.telemetryDataService = telemetryDataService;
this.wellService = wellService;
this.telemetryHubContext = telemetryHubContext;
}
protected abstract Task SignalRNotifyAsync(int idWell, IEnumerable<TDto> dtos, CancellationToken token);
/// <summary>
/// Принимает данные от разных систем по скважине
/// </summary>
/// <param name="uid">Уникальный идентификатор отправителя</param>
/// <param name="dtos">Данные</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns></returns>
[HttpPost("{uid}")]
[AllowAnonymous]
public virtual async Task<IActionResult> PostDataAsync(string uid, [FromBody] IEnumerable<TDto> dtos,
CancellationToken token)
{
await telemetryDataService.UpdateDataAsync(uid, dtos, token).ConfigureAwait(false);
var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (idWell is not null && dtos.Any())
_ = Task.Run(() => SignalRNotifyAsync(idWell.Value, dtos, CancellationToken.None));
return Ok();
}
/// <summary>
/// Возвращает данные САУБ по скважине.
/// По умолчанию за последние 10 минут.
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="begin">дата начала выборки. По умолчанию: текущее время - intervalSec</param>
/// <param name="intervalSec">интервал времени даты начала выборки, секунды</param>
/// <param name="approxPointsCount">желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена.</param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns>
[HttpGet("{idWell}")]
[Permission]
public virtual async Task<ActionResult<IEnumerable<TDto>>> GetDataAsync(int idWell,
DateTime begin = default,
int intervalSec = 600,
int approxPointsCount = 1024,
//TODO: сделать cancellationToken обязательным
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();
var content = await telemetryDataService.GetByWellAsync(idWell, begin,
intervalSec, approxPointsCount, token).ConfigureAwait(false);
return Ok(content);
}
/// <summary>
/// Новая версия. Возвращает данные САУБ по скважине.
/// По умолчанию за последние 10 минут.
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="request"></param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns>
[HttpGet("{idWell}/data")]
[Permission]
public virtual async Task<ActionResult<IEnumerable<TDto>>> GetData2Async(int idWell,
[FromQuery]TelemetryDataRequest request,
CancellationToken token)
{
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();
var content = await telemetryDataService.GetByWellAsync(idWell, request, token);
return Ok(content);
}
/// <summary>
/// Возвращает диапазон дат за которые есть телеметрия за период времени
/// </summary>
/// <param name="idWell"></param>
/// <param name="geDate"></param>
/// <param name="leDate"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("{idWell}/dateRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType((int)System.Net.HttpStatusCode.NotFound)]
[ProducesResponseType((int)System.Net.HttpStatusCode.NoContent)]
public virtual async Task<ActionResult<DatesRangeDto?>> GetRangeAsync(
[FromRoute] int idWell,
[Required] DateTimeOffset geDate,
DateTimeOffset? leDate,
CancellationToken token)
{
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();
var content = await telemetryDataService.GetRangeAsync(idWell, geDate, leDate, token);
if (content is null)
return NoContent();
return Ok(content);
}
/// <summary>
/// Возвращает диапазон дат сохраненных данных.
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns>
[HttpGet("{idWell}/datesRange")]
[Permission]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType((int)System.Net.HttpStatusCode.NotFound)]
[ProducesResponseType((int)System.Net.HttpStatusCode.NoContent)]
public virtual async Task<ActionResult<DatesRangeDto?>> GetDataDatesRangeAsync(int idWell,
CancellationToken token)
{
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();
try
{
var dataDatesRange = wellService.GetDatesRange(idWell);
return Ok(dataDatesRange);
}
catch(KeyNotFoundException)
{
return NoContent();
}
}
}