80 lines
2.3 KiB
C#
80 lines
2.3 KiB
C#
using BackupPipefy.Domain.Entities;
|
|
using BackupPipefy.Infrastructure.Data;
|
|
using BackupPipefy.Infrastructure.Services;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
public class BackupService
|
|
{
|
|
private readonly PipefyClient _client;
|
|
private readonly BackupContext _context;
|
|
private readonly int _requestsPerMinute;
|
|
|
|
public BackupService(PipefyClient client, BackupContext context, int requestsPerMinute)
|
|
{
|
|
_client = client;
|
|
_context = context;
|
|
_requestsPerMinute = requestsPerMinute;
|
|
}
|
|
|
|
public async Task RunBackup(int pipeId)
|
|
{
|
|
var control = await _context.BackupControls.FirstOrDefaultAsync();
|
|
if (control == null)
|
|
{
|
|
control = new BackupControl { LastBackupTime = DateTime.MinValue };
|
|
_context.BackupControls.Add(control);
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
|
|
DateTime startTime = DateTime.Now;
|
|
|
|
string json = await _client.GetCardsAsync(pipeId, control.LastBackupTime);
|
|
|
|
var doc = System.Text.Json.JsonDocument.Parse(json);
|
|
var edges = doc.RootElement.GetProperty("data")
|
|
.GetProperty("allCards")
|
|
.GetProperty("edges");
|
|
|
|
int count = 0;
|
|
int delayMs = (int)(60000 / _requestsPerMinute);
|
|
|
|
foreach (var edge in edges.EnumerateArray())
|
|
{
|
|
var node = edge.GetProperty("node");
|
|
long id = long.Parse(node.GetProperty("id").GetString());
|
|
|
|
var card = await _context.PipefyCards.FindAsync(id);
|
|
if (card != null)
|
|
{
|
|
card.JsonData = node.GetRawText();
|
|
}
|
|
else
|
|
{
|
|
await _context.PipefyCards.AddAsync(new PipefyCard
|
|
{
|
|
Id = id,
|
|
JsonData = node.GetRawText()
|
|
});
|
|
}
|
|
|
|
count++;
|
|
await Task.Delay(delayMs);
|
|
}
|
|
|
|
await _context.SaveChangesAsync();
|
|
|
|
// Atualiza o controle de backup
|
|
control.LastBackupTime = startTime;
|
|
await _context.SaveChangesAsync();
|
|
|
|
// Grava log
|
|
_context.BackupLogs.Add(new BackupLog
|
|
{
|
|
ExecutionTime = startTime,
|
|
Status = "SUCCESS",
|
|
RecordsProcessed = count
|
|
});
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
}
|