Skip to content

Commit

Permalink
Merge pull request #34 from pimmerks/fix/http-client-disposed-fix
Browse files Browse the repository at this point in the history
Fixed Http client being disposed
  • Loading branch information
pimmerks authored Apr 28, 2020
2 parents 8648e24 + d52d7fb commit ab92b8c
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 93 deletions.
103 changes: 17 additions & 86 deletions ExampleConsoleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,18 @@

public class Program
{
private string clientSecret;
private string clientId;
private string redirectUri;
private AuthParameters parameters;
private readonly IConfiguration configuration;
private readonly SpotifyAuthentication spotifyAuthentication;

public Program(IConfiguration configuration)
public Program(IConfiguration configuration, SpotifyAuthentication spotifyAuthentication)
{
this.clientId = configuration["Spotify:ClientId"];
this.clientSecret = configuration["Spotify:ClientSecret"];
this.redirectUri = configuration["Spotify:RedirectUri"];

parameters = new AuthParameters
{
ClientId = this.clientId,
ClientSecret = this.clientSecret,
RedirectUri = this.redirectUri,
Scopes = Scopes.All,
ShowDialog = true
};
this.configuration = configuration;
this.spotifyAuthentication = spotifyAuthentication;
}

public async Task Run()
{
var token = await this.GetToken();
var token = await this.spotifyAuthentication.GetToken();

Console.Clear();
Console.WriteLine("Successfully logged in!");
Expand All @@ -50,12 +38,8 @@ public async Task Run()

var playlists = await api.Playlist.GetMyPlaylists();
Console.WriteLine("Your playlists:");
foreach (var simplePlaylist in playlists)
{
Console.Write($"{simplePlaylist.Name}, ");
}
Console.WriteLine(string.Join(", ", playlists.Select(x => x.Name)));

Console.WriteLine();
Console.WriteLine();

var devices = await api.Player.GetAvailableDevices();
Expand All @@ -65,71 +49,18 @@ public async Task Run()
Console.Write($"{device.Name}, ");
}

Console.WriteLine("Refreshing token...");
var newToken = await AuthorizationCode.RefreshTokenAsync(this.parameters, token);
Console.WriteLine($"old: {token.AccessToken}");
Console.WriteLine($"new: {newToken.AccessToken}");

api.SetToken(newToken);

me = await api.UserProfile.GetMe();

Console.WriteLine($"Hello {me.DisplayName}");
// Console.WriteLine("Refreshing token...");
// var newToken = await AuthorizationCode.RefreshTokenAsync(this.parameters, token);
// Console.WriteLine($"old: {token.AccessToken}");
// Console.WriteLine($"new: {newToken.AccessToken}");
//
// api.SetToken(newToken);
//
// me = await api.UserProfile.GetMe();
//
// Console.WriteLine($"Hello {me.DisplayName}");

Console.ReadLine();
}

public async Task<Token> GetToken()
{
var state = Guid.NewGuid().ToString(); // Save this state because you must check it later



var url = AuthorizationCode.GetUrl(this.parameters, state);

Console.WriteLine("Opening url...");
Console.WriteLine(url);

var ps = new ProcessStartInfo(url)
{
UseShellExecute = true,
Verb = "open"
};
Process.Start(ps);

var queryString = await this.StartServerAndRetrieveAuthCode();

// The retrieved callback:
var retrievedState = queryString["state"];
var retrievedCode = queryString["code"];
var retrievedError = queryString["error"];

if (retrievedError != null)
{
throw new Exception(retrievedError);
}

if (state != retrievedState)
{
throw new Exception("State did not match!");
}

var token = await AuthorizationCode.ProcessCallbackAsync(this.parameters, retrievedCode);

return token;
}

public async Task<NameValueCollection> StartServerAndRetrieveAuthCode(string url = "http://localhost:8080/")
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();

var context = await listener.GetContextAsync();

listener.Stop();

return context.Request.QueryString;
}
}
}
87 changes: 87 additions & 0 deletions ExampleConsoleApp/SpotifyAuthentication.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
namespace ExampleConsoleApp
{
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using SpotifyWebApi.Auth;
using SpotifyWebApi.Model.Auth;
using SpotifyWebApi.Model.Enum;

public class SpotifyAuthentication
{
private string clientSecret;
private string clientId;
private string redirectUri;
private AuthParameters parameters;

public SpotifyAuthentication(IConfiguration configuration)
{
this.clientId = configuration["Spotify:ClientId"];
this.clientSecret = configuration["Spotify:ClientSecret"];
this.redirectUri = configuration["Spotify:RedirectUri"];

this.parameters = new AuthParameters
{
ClientId = this.clientId,
ClientSecret = this.clientSecret,
RedirectUri = this.redirectUri,
Scopes = Scopes.All,
ShowDialog = true
};
}

public async Task<Token> GetToken()
{
var state = Guid.NewGuid().ToString(); // Save this state because you must check it later

var url = AuthorizationCode.GetUrl(this.parameters, state);

Console.WriteLine("Opening url...");
Console.WriteLine(url);

var ps = new ProcessStartInfo(url)
{
UseShellExecute = true,
Verb = "open"
};
Process.Start(ps);

var queryString = await this.StartServerAndRetrieveAuthCode();

// The retrieved callback:
var retrievedState = queryString["state"];
var retrievedCode = queryString["code"];
var retrievedError = queryString["error"];

if (retrievedError != null)
{
throw new Exception(retrievedError);
}

if (state != retrievedState)
{
throw new Exception("State did not match!");
}

var token = await AuthorizationCode.ProcessCallbackAsync(this.parameters, retrievedCode);

return token;
}

public async Task<NameValueCollection> StartServerAndRetrieveAuthCode(string url = "http://localhost:8080/")
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();

var context = await listener.GetContextAsync();

listener.Stop();

return context.Request.QueryString;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using System;

namespace ExampleConsoleApp
namespace ExampleConsoleApp
{
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SpotifyWebApi.Model.Enum;

class Bootstrap
class Startup
{
static async Task Main(string[] args)
{
Expand All @@ -22,13 +19,13 @@ static async Task Main(string[] args)
IConfiguration configuration = builder.Build();

serviceCollection.AddScoped<IConfiguration>(_ => configuration);
serviceCollection.AddScoped<SpotifyAuthentication>();
serviceCollection.AddScoped<Program>();

var serviceProvider = serviceCollection.BuildServiceProvider();

var p = serviceProvider.GetRequiredService<Program>();
await p.Run();

}
}
}
2 changes: 1 addition & 1 deletion SpotifyWebApi/Business/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public static async Task<WebResponse> DeleteAsync<T>(Uri uri, Token token = null
/// <returns>A newly created <see cref="HttpClient"/> containing the authentication provided by the token.</returns>
private static HttpClient MakeHttpClient(Token token = null)
{
using var client = new HttpClient();
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/x-www-form-urlencoded"));

if (token != null)
Expand Down

0 comments on commit ab92b8c

Please sign in to comment.