59 lines
1.9 KiB
C#
59 lines
1.9 KiB
C#
using System.Globalization;
|
|
using Google.Apis.Sheets.v4;
|
|
using Google.Apis.Sheets.v4.Data;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using WebAPI.Models;
|
|
|
|
namespace WebAPI.Controllers;
|
|
|
|
public class LogsController : Controller
|
|
{
|
|
private readonly SpreadsheetsResource.ValuesResource? _googleSheetValues;
|
|
private readonly IConfiguration _configuration;
|
|
public LogsController(
|
|
GoogleSheetsHelper googleSheetsHelper,
|
|
IConfiguration configuration)
|
|
{
|
|
if (googleSheetsHelper.Service is not null) {
|
|
_googleSheetValues = googleSheetsHelper.Service.Spreadsheets.Values;
|
|
}
|
|
_configuration = configuration;
|
|
}
|
|
|
|
public void AddEntry(LogEntry entry)
|
|
{
|
|
if (_googleSheetValues is null) {
|
|
throw new Exception("Google Sheets API not initialized");
|
|
}
|
|
|
|
var type = entry.LogType switch
|
|
{
|
|
LogType.Import => "Import",
|
|
LogType.Backup => "Backup",
|
|
LogType.Process => "Process",
|
|
LogType.PowerBi => "PowerBIAccess",
|
|
_ => "Other"
|
|
};
|
|
var response = _googleSheetValues.Get(_configuration["appLogsFile"], $"{type}!A:A").Execute();
|
|
var data = response.Values;
|
|
var row = 1;
|
|
if (data != null) {
|
|
row = data.Count + 1;
|
|
}
|
|
var range = $"{type}!A{row}:D{row}";
|
|
|
|
var logRow = new List<object>
|
|
{
|
|
entry.CreatedAt.ToString(new CultureInfo("pl-PL")),
|
|
entry.Type.ToString(),
|
|
entry.Title!,
|
|
entry.Message!
|
|
};
|
|
|
|
var valueRange = new ValueRange { Values = new IList<object>[] { logRow }};
|
|
|
|
var updateRequest = _googleSheetValues.Update(valueRange, _configuration["appLogsFile"], range);
|
|
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
|
|
updateRequest.Execute();
|
|
}
|
|
} |