Files
tsGmail/GmailTokenManager.cs

58 lines
1.9 KiB
C#

using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
public static class GmailTokenManager
{
//public static async Task<string> ObtenerAccessTokenAsync(GmailConfig config)
//{
// var stream = new MemoryStream(config.ClientSecret);
// var credencial = await GoogleWebAuthorizationBroker.AuthorizeAsync(
// GoogleClientSecrets.FromStream(stream).Secrets,
// new[] { "https://mail.google.com/" },
// config.Usuario,
// CancellationToken.None,
// new FileDataStore(config.TokenFolder, true)
// );
// return await credencial.GetAccessTokenForRequestAsync();
//}
private static readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
public static async Task<string> ObtenerAccessTokenAsync(GmailConfig config)
{
var stream = new MemoryStream(config.ClientSecret);
int i = 0;
do
{
i++;
await _tokenSemaphore.WaitAsync();
try
{
var credencial = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
new[] { "https://mail.google.com/" },
config.Usuario,
CancellationToken.None,
new FileDataStore(config.TokenFolder, true)
);
return await credencial.GetAccessTokenForRequestAsync();
}
catch (Exception ex)
{
if (i > 1) throw new Exception(ex.Message,ex);
System.Threading.Thread.Sleep(5000);
}
finally
{
_tokenSemaphore.Release();
}
}
while (true);
}
}