Files
DiunaBI/src/Backend/DiunaBI.Infrastructure/Services/GoogleSheetsHelper.cs

55 lines
2.0 KiB
C#
Raw Normal View History

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
Console.WriteLine($"[GoogleSheetsHelper] Original JSON length: {json.Length}");
Console.WriteLine($"[GoogleSheetsHelper] First 200 chars: {json.Substring(0, Math.Min(200, json.Length))}");
// Replace literal \n with actual newlines
2025-11-18 20:38:35 +01:00
json = json.Replace("\\n", "\n");
2025-11-19 17:53:02 +01:00
Console.WriteLine($"[GoogleSheetsHelper] After replacement, first 200 chars: {json.Substring(0, Math.Min(200, json.Length))}");
try
{
return GoogleCredential.FromJson(json).CreateScoped(Scopes);
}
catch (Exception ex)
{
Console.WriteLine($"[GoogleSheetsHelper] ERROR parsing JSON: {ex.Message}");
Console.WriteLine($"[GoogleSheetsHelper] JSON being parsed: {json}");
throw;
}
2025-11-18 20:38:35 +01:00
#endif
}
}