|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using SpotifyAPI.Web.Enums; |
| 8 | +using SpotifyAPI.Web.Models; |
| 9 | + |
| 10 | +namespace SpotifyAPI.Web.Auth |
| 11 | +{ |
| 12 | + public class AuthenticationFactory |
| 13 | + { |
| 14 | + private readonly string m_RedirectUrl; |
| 15 | + private readonly int m_ListeningPort; |
| 16 | + private readonly string m_ClientId; |
| 17 | + private readonly TimeSpan m_Timeout; |
| 18 | + private Scope m_Scope; |
| 19 | + |
| 20 | + public AuthenticationFactory(string redirectUrl, int listeningPort, string clientId, Scope scope, TimeSpan timeout) |
| 21 | + { |
| 22 | + m_RedirectUrl = redirectUrl; |
| 23 | + m_ListeningPort = listeningPort; |
| 24 | + m_ClientId = clientId; |
| 25 | + m_Scope = scope; |
| 26 | + m_Timeout = timeout; |
| 27 | + } |
| 28 | + |
| 29 | + public Task<SpotifyWebAPI> GetWebApi() |
| 30 | + { |
| 31 | + var authentication = new ImplicitGrantAuth |
| 32 | + { |
| 33 | + RedirectUri = $"{m_RedirectUrl}:{m_ListeningPort}", |
| 34 | + ClientId = m_ClientId, |
| 35 | + Scope = m_Scope, |
| 36 | + State = "XSS" |
| 37 | + }; |
| 38 | + |
| 39 | + AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false); |
| 40 | + SpotifyWebAPI spotifyWebApi = null; |
| 41 | + authentication.OnResponseReceivedEvent += (token, state) => |
| 42 | + { |
| 43 | + spotifyWebApi = HandleSpotifyResponse(state, token); |
| 44 | + authenticationWaitFlag.Set(); |
| 45 | + }; |
| 46 | + |
| 47 | + authentication.StartHttpServer(m_ListeningPort); |
| 48 | + |
| 49 | + authentication.DoAuth(); |
| 50 | + |
| 51 | + authenticationWaitFlag.WaitOne(m_Timeout); |
| 52 | + if (spotifyWebApi == null) |
| 53 | + throw new TimeoutException($"No valid response received for the last {m_Timeout.TotalSeconds} seconds"); |
| 54 | + |
| 55 | + authentication.StopHttpServer(); |
| 56 | + |
| 57 | + return Task.FromResult(spotifyWebApi); |
| 58 | + } |
| 59 | + |
| 60 | + private static SpotifyWebAPI HandleSpotifyResponse(string state, Token token) |
| 61 | + { |
| 62 | + if (state != "XSS") |
| 63 | + throw new SpotifyWebApiException($"Wrong state '{state}' received."); |
| 64 | + |
| 65 | + if (token.Error != null) |
| 66 | + throw new SpotifyWebApiException($"Error: {token.Error}"); |
| 67 | + |
| 68 | + var spotifyWebApi = new SpotifyWebAPI |
| 69 | + { |
| 70 | + UseAuth = true, |
| 71 | + AccessToken = token.AccessToken, |
| 72 | + TokenType = token.TokenType |
| 73 | + }; |
| 74 | + |
| 75 | + return spotifyWebApi; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + [Serializable] |
| 80 | + public class SpotifyWebApiException : Exception |
| 81 | + { |
| 82 | + public SpotifyWebApiException(string message) : base(message) |
| 83 | + { } |
| 84 | + } |
| 85 | +} |
0 commit comments