diff --git a/SpotifyApi.cs b/SpotifyApi.cs index ac430f2..5a4b765 100644 --- a/SpotifyApi.cs +++ b/SpotifyApi.cs @@ -8,6 +8,7 @@ using SpotifyAPI.Local.Enums; using SpotifyAPI.Local.Models; using SpotifyAPI.Web; +using SpotifyAPI.Web.Auth; using SpotifyAPI.Web.Enums; using SpotifyAPI.Web.Models; @@ -16,7 +17,7 @@ namespace Wox.Plugin.Spotify public class SpotifyApi { private readonly SpotifyLocalAPI _localSpotify; - private readonly SpotifyWebAPI _spotifyApi; + private SpotifyWebAPI _spotifyApi; private readonly object _lock = new object(); @@ -34,13 +35,9 @@ public SpotifyApi(string pluginDir = null) _localSpotify.OnPlayStateChange += (o, e) => IsPlaying = e.Playing; ConnectToSpotify(); - _spotifyApi = new SpotifyWebAPI - { - UseAuth = false - }; + _spotifyApi = new SpotifyWebAPI(); } - public bool IsPlaying { get; set; } public bool IsMuted => _localSpotify.IsSpotifyMuted(); @@ -51,6 +48,8 @@ public SpotifyApi(string pluginDir = null) public bool IsConnected { get; private set; } + public bool IsWebApiCOnnected => !string.IsNullOrEmpty(_spotifyApi.AccessToken); + public bool IsRunning => SpotifyLocalAPI.IsSpotifyRunning() && SpotifyLocalAPI.IsSpotifyWebHelperRunning(); public void Play() @@ -91,6 +90,12 @@ public void RunSpotify() SpotifyLocalAPI.RunSpotify(); } + public async Task ConnectWebApi() + { + var webApiFactory = new WebAPIFactory("http://localhost", 8000, "3e271cd3f0634b92a991f60601f9db44", Scope.None, TimeSpan.FromSeconds(40)); + _spotifyApi = await webApiFactory.GetWebApi(); + } + public IEnumerable GetArtists(string s) { lock (_lock) diff --git a/SpotifyPlugin.cs b/SpotifyPlugin.cs index 4998bc3..394d0b8 100644 --- a/SpotifyPlugin.cs +++ b/SpotifyPlugin.cs @@ -216,6 +216,8 @@ public List Query(Query query) private List SearchTrack(string param) { + if (!_api.IsWebApiCOnnected) return AuthenticateResult; + if (string.IsNullOrWhiteSpace(param)) { return new List(); @@ -240,6 +242,8 @@ private List SearchTrack(string param) private List SearchAlbum(string param) { + if (!_api.IsWebApiCOnnected) return AuthenticateResult; + if (string.IsNullOrWhiteSpace(param)) { return new List(); @@ -264,6 +268,8 @@ private List SearchAlbum(string param) private List SearchArtist(string param) { + if (!_api.IsWebApiCOnnected) return AuthenticateResult; + if (string.IsNullOrWhiteSpace(param)) { return new List(); @@ -286,5 +292,24 @@ private List SearchArtist(string param) Task.WaitAll(results); return results.Select(x => x.Result).ToList(); } + + private List AuthenticateResult => new List() + { + new Result() + { + Title = "Authentication required to search the Spotify library", + SubTitle = "Click this to authenticate", + IcoPath = SpotifyIcon, + Action = _ => { + // This will prompt the user to authenticate + var t = new System.Threading.Thread(async () => { + await _api.ConnectWebApi(); + }); + t.Start(); + + return true; + } + } + }; } } \ No newline at end of file