using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Responses; using System; using System.Threading; using System.Threading.Tasks; namespace YouTube.Authorization { public class UserCredential : Google.Apis.Auth.OAuth2.UserCredential { /// /// Event is fired when new refresh token is recieved and the old one is no loger valid /// public event EventHandler RefreshTokenUpdated; /// Constructs a new credential instance. /// Authorization code flow. /// User identifier. /// An initial token for the user. public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token) : base(flow, userId, token) { } /// Constructs a new credential instance. /// Authorization code flow. /// User identifier. /// An initial token for the user. /// The ID of the project associated /// to this credential for the purposes of quota calculation and billing. Can be null. public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token, string quotaProjectId) : base(flow, userId, token, quotaProjectId) { } /// /// Refreshes the token by calling to /// . /// Then it updates the with the new token instance. /// /// Cancellation token to cancel an operation. /// true if the token was refreshed. public new async Task RefreshTokenAsync(CancellationToken taskCancellationToken) { if (Token.RefreshToken == null) { Logger.Warning("Refresh token is null, can't refresh the token!"); return false; } // It's possible that two concurrent calls will be made to refresh the token, in that case the last one // will win. var newToken = await Flow.RefreshTokenAsync(UserId, Token.RefreshToken, taskCancellationToken) .ConfigureAwait(false); Logger.Info("Access token was refreshed successfully"); if (newToken.RefreshToken == null) newToken.RefreshToken = Token.RefreshToken; Token = newToken; RefreshTokenUpdated?.Invoke(this, null); return true; } } }