var item = await _ctx.Telemetry.FirstOrDefaultAsync(x=>x.Login == model.Login && // совпадение по логину
x.PageName == topic.Title && // совпадение по имени курса
x.PageNumber == topic.Path // совпадение по пути
);
if (!ModelState.IsValid) return BadRequest();
var now = DateTime.UtcNow;
model.Login = FixLoginNames(model.Login);
var m = await _ctx.Telemetry.OrderByDescending(x => x.End)
.FirstOrDefaultAsync(x => x.Login == model.Login &&
x.CourseId == model.CourseId &&
x.PageName == model.PageName &&
x.PageNumber == model.PageNumber);
try
{
var id = 0L;
model.Start = now;
var endTime = now.AddSeconds(Interval + 1);
if (model.Topics != null) await ParseTopics(model, now);
if (m == null)
{
model.End = endTime;
await _ctx.AddAsync(model);
await _ctx.SaveChangesAsync();
id = model.Id;
}
// Проверяем что это одна и та-же сессия
else if (m?.End != null && m.End > now)
{
m.End = endTime;
m.Duration = GetDuration(m);
_ctx.Telemetry.Update(m);
await _ctx.SaveChangesAsync();
id = m.Id;
}
else
{
model.End = now;
model.Duration = 0;
await _ctx.AddAsync(model);
await _ctx.SaveChangesAsync();
id = model.Id;
}
var url = Url.Action("Get", new { id });
return Created(url, new { id, url });
}
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureLogging(loggerFactory => loggerFactory.AddEventLog())
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ServiceTelemetry>();
})
.ConfigureWebHostDefaults(webBuilder =>
{
var fileName = Process.GetCurrentProcess().MainModule.FileName;
var procDirectory = Directory.GetParent(fileName).FullName;
var appSettings = Path.Combine(procDirectory, "appsettings.json");
var config = new ConfigurationBuilder()
.SetBasePath(procDirectory)
.AddEnvironmentVariables()
.AddJsonFile(appSettings)
.AddCommandLine(args)
.Build();
webBuilder
.UseConfiguration(config)
.UseStartup<Startup>();
});
public void ConfigureServices(IServiceCollection services)
{
var con = _configuration.GetConnectionString("telemetry");
services.AddDbContext<TelemetryContext>(options => options.UseSqlServer(con));
}
[ApiController]
[Route("api/[controller]")]
public class TelemetryController : ControllerBase
{
private const int Interval = 15;
private readonly TelemetryContext _ctx;
public TelemetryController(TelemetryContext context)
{
_ctx = context;
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Post(TelemetryModel model)
{
if (ModelState.IsValid)
{