Skip to content

Commit

Permalink
Implement retrying behavior when initializing token
Browse files Browse the repository at this point in the history
  • Loading branch information
calledude committed Mar 6, 2024
1 parent f6f780c commit bb57078
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions SpotifyVolumeExtension/Spotify/TokenInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Swan.Logging;
using System;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Web;
Expand All @@ -25,23 +26,35 @@ public TokenInitializer()

public async Task<AuthorizationCodeTokenResponse> InitializeToken()
{
// TODO: Need to implement retrying behavior
const int attemptTimeoutInSeconds = 25;
var logger = Log.Logger.ForContext<TokenInitializer>();
logger.Information("Trying to authenticate with Spotify. This might take up to {timeout} seconds", 25);
logger.Information("Trying to authenticate with Spotify. This might take up to {timeout} seconds", attemptTimeoutInSeconds);

// TODO: Abstract this away into a separate class akin to LoginRequest
var builder = new StringBuilder(TokenSwapAuthenticator.AuthorizeUri);
builder.Append("?response_type=code");
builder.Append($"&redirect_uri={HttpUtility.UrlEncode(TokenSwapAuthenticator.ExchangeServerUrl)}");
builder.Append($"&scope={HttpUtility.UrlEncode(string.Join(" ", Scopes.UserModifyPlaybackState, Scopes.UserReadPlaybackState))}");

BrowserUtil.Open(new Uri(builder.ToString()));
var authUri = new Uri(builder.ToString());
BrowserUtil.Open(authUri);

await _server.Start();

var tokenResponse = await _channel.Reader.ReadAsync();
logger.Information("Successfully authenticated.");
return tokenResponse;
while (true)
{
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(attemptTimeoutInSeconds));
var tokenResponse = await _channel.Reader.ReadAsync(cts.Token).AsTask();
logger.Information("Successfully authenticated.");
return tokenResponse;
}
catch (OperationCanceledException)
{
logger.Warning("Authentication attempt timed out. Retrying.");
BrowserUtil.Open(authUri);
}
}
}

private async Task OnAuthorizationCodeReceived(object obj, AuthorizationCodeResponse code)
Expand Down

0 comments on commit bb57078

Please sign in to comment.