Files
DiunaBI/WebAPI/Controllers/LogsController.cs

70 lines
2.5 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 Microsoft.EntityFrameworkCore;
using WebAPI.Models;
namespace WebAPI.Controllers
{
public class LogsController : Controller
{
2023-11-29 22:14:37 +01:00
private SpreadsheetsResource.ValuesResource? googleSheetValues;
2023-08-29 14:55:31 +02:00
private GoogleDriveHelper googleDriveHelper;
private readonly IConfiguration configuration;
public LogsController(
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
2023-11-29 22:14:37 +01:00
if (_googleSheetsHelper.Service is not null) {
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
}
2023-08-29 14:55:31 +02:00
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
}
public void AddEntry(LogEntry entry)
{
2023-11-29 22:14:37 +01:00
if (googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
2023-08-29 14:55:31 +02:00
String type;
switch (entry.LogType) {
case LogType.import:
type = "Import";
break;
2023-09-01 18:23:53 +02:00
case LogType.backup:
type = "Backup";
break;
2023-09-17 13:00:24 +02:00
case LogType.process:
type = "Process";
break;
2023-08-29 14:55:31 +02:00
default:
type = "Other"; // should never happen
break;
}
var response = googleSheetValues.Get(configuration["appLogsFile"], $"{type}!A:A").Execute();
var data = response.Values;
2023-08-31 16:54:04 +02:00
int row = 1;
2023-11-29 22:14:37 +01:00
if (data != null) {
row = data.Count + 1;
2023-08-31 16:54:04 +02:00
}
2023-08-29 14:55:31 +02:00
var range = $"{type}!A{row}:D{row}";
List<object> logRow = new List<object>
{
entry.CreatedAt.ToString(new CultureInfo("pl-PL")),
entry.Type.ToString(),
entry.Title!,
entry.Message!
};
ValueRange 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();
}
}
}