2025-11-18 20:38:35 +01:00
|
|
|
|
using Google.Apis.Auth.OAuth2;
|
|
|
|
|
|
using Google.Apis.Services;
|
|
|
|
|
|
using Google.Apis.Sheets.v4;
|
|
|
|
|
|
|
|
|
|
|
|
namespace DiunaBI.Infrastructure.Services;
|
|
|
|
|
|
|
|
|
|
|
|
public class GoogleSheetsHelper
|
|
|
|
|
|
{
|
|
|
|
|
|
public SheetsService? Service { get; private set; }
|
|
|
|
|
|
private const string ApplicationName = "Diuna";
|
|
|
|
|
|
private static readonly string[] Scopes = [SheetsService.Scope.Spreadsheets];
|
|
|
|
|
|
public GoogleSheetsHelper()
|
|
|
|
|
|
{
|
|
|
|
|
|
InitializeService();
|
|
|
|
|
|
}
|
|
|
|
|
|
private void InitializeService()
|
|
|
|
|
|
{
|
|
|
|
|
|
var credential = GetCredentialsFromFile();
|
|
|
|
|
|
Service = new SheetsService(new BaseClientService.Initializer
|
|
|
|
|
|
{
|
|
|
|
|
|
HttpClientInitializer = credential,
|
|
|
|
|
|
ApplicationName = ApplicationName
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
private static GoogleCredential GetCredentialsFromFile()
|
|
|
|
|
|
{
|
|
|
|
|
|
#if DEBUG
|
|
|
|
|
|
using var stream = new FileStream("client_secrets.Development.json", FileMode.Open, FileAccess.Read);
|
|
|
|
|
|
return GoogleCredential.FromStream(stream).CreateScoped(Scopes);
|
|
|
|
|
|
#else
|
|
|
|
|
|
var json = Environment.GetEnvironmentVariable("GOOGLE_SERVICE_ACCOUNT_JSON");
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(json))
|
|
|
|
|
|
throw new InvalidOperationException("GOOGLE_SERVICE_ACCOUNT_JSON environment variable is not set.");
|
2025-11-19 17:53:02 +01:00
|
|
|
|
|
2025-11-19 18:30:55 +01:00
|
|
|
|
Console.WriteLine($"[GoogleSheetsHelper] Loading credentials from environment variable (length: {json.Length})");
|
2025-11-19 17:53:02 +01:00
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
return GoogleCredential.FromJson(json).CreateScoped(Scopes);
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
2025-11-19 18:30:55 +01:00
|
|
|
|
Console.WriteLine($"[GoogleSheetsHelper] ERROR: Failed to parse credentials - {ex.Message}");
|
|
|
|
|
|
throw new InvalidOperationException("Failed to parse Google service account credentials. Ensure GOOGLE_SERVICE_ACCOUNT_JSON is properly formatted.", ex);
|
2025-11-19 17:53:02 +01:00
|
|
|
|
}
|
2025-11-18 20:38:35 +01:00
|
|
|
|
#endif
|
|
|
|
|
|
}
|
2025-05-31 19:26:02 +02:00
|
|
|
|
}
|