Spotify.NET/SpotifyAPI/Web/Auth/WebApiFactory.cs

96 lines
2.9 KiB
C#
Raw Normal View History

2016-07-19 20:15:22 +01:00
using System;
using System.Threading;
using System.Threading.Tasks;
using SpotifyAPI.Web.Enums;
using SpotifyAPI.Web.Models;
namespace SpotifyAPI.Web.Auth
{
2016-07-29 23:19:57 +01:00
public class WebAPIFactory
2016-07-19 20:15:22 +01:00
{
2016-07-29 23:19:57 +01:00
private readonly string _redirectUrl;
private readonly int _listeningPort;
private readonly string _clientId;
private readonly TimeSpan _timeout;
private readonly Scope _scope;
private readonly string _xss;
2016-07-19 20:15:22 +01:00
public WebAPIFactory(string redirectUrl, int listeningPort, string clientId, Scope scope)
: this(redirectUrl, listeningPort, clientId, scope, TimeSpan.FromSeconds(20))
{
}
public WebAPIFactory(string redirectUrl, int listeningPort, string clientId, Scope scope, TimeSpan timeout, string xss = "XSS")
2016-07-19 20:15:22 +01:00
{
2016-07-29 23:19:57 +01:00
_redirectUrl = redirectUrl;
_listeningPort = listeningPort;
_clientId = clientId;
_scope = scope;
_timeout = timeout;
_xss = xss;
2016-07-19 20:15:22 +01:00
}
public Task<SpotifyWebAPI> GetWebApi()
{
var authentication = new ImplicitGrantAuth
{
2016-07-29 23:19:57 +01:00
RedirectUri = $"{_redirectUrl}:{_listeningPort}",
ClientId = _clientId,
Scope = _scope,
State = _xss
2016-07-19 20:15:22 +01:00
};
AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false);
SpotifyWebAPI spotifyWebApi = null;
authentication.OnResponseReceivedEvent += (token, state) =>
{
spotifyWebApi = HandleSpotifyResponse(state, token);
authenticationWaitFlag.Set();
};
try
{
2016-07-29 23:19:57 +01:00
authentication.StartHttpServer(_listeningPort);
2016-07-19 20:15:22 +01:00
authentication.DoAuth();
2016-07-19 20:15:22 +01:00
2016-07-29 23:19:57 +01:00
authenticationWaitFlag.WaitOne(_timeout);
if (spotifyWebApi == null)
2016-07-29 23:19:57 +01:00
throw new TimeoutException($"No valid response received for the last {_timeout.TotalSeconds} seconds");
}
finally
{
authentication.StopHttpServer();
}
2016-07-19 20:15:22 +01:00
return Task.FromResult(spotifyWebApi);
}
private SpotifyWebAPI HandleSpotifyResponse(string state, Token token)
2016-07-19 20:15:22 +01:00
{
if (state != _xss)
2016-07-19 20:15:22 +01:00
throw new SpotifyWebApiException($"Wrong state '{state}' received.");
if (token.Error != null)
throw new SpotifyWebApiException($"Error: {token.Error}");
var spotifyWebApi = new SpotifyWebAPI
{
UseAuth = true,
AccessToken = token.AccessToken,
TokenType = token.TokenType
};
return spotifyWebApi;
}
}
[Serializable]
public class SpotifyWebApiException : Exception
{
public SpotifyWebApiException(string message) : base(message)
{ }
}
}