Files
DiunaBI/WebAPI/Controllers/LogsController.cs

59 lines
1.9 KiB
C#
Raw Normal View History

2023-08-29 14:55:31 +02:00
using System.Globalization;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Microsoft.AspNetCore.Mvc;
using WebAPI.Models;
2024-06-18 19:40:16 +02:00
namespace WebAPI.Controllers;
public class LogsController : Controller
2023-08-29 14:55:31 +02:00
{
2024-06-18 19:40:16 +02:00
private readonly SpreadsheetsResource.ValuesResource? _googleSheetValues;
private readonly IConfiguration _configuration;
public LogsController(
GoogleSheetsHelper googleSheetsHelper,
IConfiguration configuration)
2023-08-29 14:55:31 +02:00
{
2024-06-18 19:40:16 +02:00
if (googleSheetsHelper.Service is not null) {
_googleSheetValues = googleSheetsHelper.Service.Spreadsheets.Values;
2023-08-29 14:55:31 +02:00
}
2024-06-18 19:40:16 +02:00
_configuration = configuration;
}
2023-08-29 14:55:31 +02:00
2024-06-18 19:40:16 +02:00
public void AddEntry(LogEntry entry)
{
if (_googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
var type = entry.LogType switch
2023-08-29 14:55:31 +02:00
{
2024-06-18 19:40:16 +02:00
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}";
2023-08-29 14:55:31 +02:00
2024-06-18 19:40:16 +02:00
var logRow = new List<object>
{
entry.CreatedAt.ToString(new CultureInfo("pl-PL")),
entry.Type.ToString(),
entry.Title!,
entry.Message!
};
2023-08-29 14:55:31 +02:00
2024-06-18 19:40:16 +02:00
var valueRange = new ValueRange { Values = new IList<object>[] { logRow }};
2023-08-29 14:55:31 +02:00
2024-06-18 19:40:16 +02:00
var updateRequest = _googleSheetValues.Update(valueRange, _configuration["appLogsFile"], range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
updateRequest.Execute();
2023-08-29 14:55:31 +02:00
}
}