public async void ConnectToAPI()
        {
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                data._clientId,
                Scope.UserReadPrivate,
                TimeSpan.FromSeconds(20)
                );

            try
            {
                //This will open the user's browser and returns once
                //the user is authorized.
                _spotify = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (_spotify == null)
            {
                return;
            }
            else
            {
                currentForm.HideSpotifyButton();
                Console.WriteLine("Connected to Spotify.");
            }
        }
        public SpotifyConnection(MainForm newForm)
        {
            currentForm = newForm;

            string thisFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            thisFolder = thisFolder.Substring(0, thisFolder.LastIndexOf("AlbumArt"));

            string jsonPath = thisFolder + "\\SpotifyAuthData.json";

            if (File.Exists(jsonPath))
            {
                data = JsonConvert.DeserializeObject <ConnectionData>(File.ReadAllText(jsonPath));
            }
            else
            {
                StreamWriter writer = File.CreateText(jsonPath);
                writer.Write(JsonConvert.SerializeObject(data));
                writer.Close();
            }


            _spotify = new SpotifyWebAPI()
            {
                UseAuth = false,
            };
        }
예제 #3
0
        public async static void AuthenticateSpotifyWeb()
        {
            //Check first if we already have a token from Spotify.
            if (ApplicationData.Default.SpotifyToken != "")
            {
                spotWeb             = new SpotifyWebAPI();
                spotWeb.AccessToken = ApplicationData.Default.SpotifyToken;
                spotWeb.TokenType   = "Bearer";
                SpotifyAPI.Web.Models.PrivateProfile pp = spotWeb.GetPrivateProfile();
                if (!pp.HasError())
                {
                    // success

                    return;
                }
                else
                {
                    //failed, is token invalid ?
#if DEBUG
                    MessageBox.Show("Auth from saved token failed.");
#endif
                    spotWeb.Dispose();
                }
            }



            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => System.Windows.MessageBox.Show("Please sign in, to be able to show your play lists.")),
                                                                              System.Windows.Threading.DispatcherPriority.Normal);
            WebAPIFactory webApiFactory = new WebAPIFactory(
                "http://localhost",
                8000,
                "3a922edff6af43e9be7abb98cf217220",
                Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadRecentlyPlayed | Scope.UserTopRead,
                TimeSpan.FromSeconds(60)
                );

            try
            {
                //This will open the user's browser and returns once
                //the user is authorized.
                spotWeb = await webApiFactory.GetWebApi();
            }
            catch (Exception ex)
            {
                spotWeb = null;
                MessageBox.Show(ex.Message);
            }

            if (spotWeb == null)
            {
                return;
            }

            Console.WriteLine("Token retreived succesfully from spotify web service.");
            ApplicationData.Default.SpotifyToken = spotWeb.AccessToken;
            ApplicationData.Default.Save();
            return;
        }
    /// <summary>
    /// Gets all elements of a paging list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="api">A reference to the api</param>
    /// <param name="pagingList">The list to get the rest of</param>
    /// <returns></returns>
    public static async Task <List <T> > GetAllFromPagingAsync <T>(SpotifyAPI.Web.SpotifyWebAPI api, SAPIModels.Paging <T> pagingList) where T : class
    {
        List <T> returnList = new List <T>(pagingList.Items);

        while (pagingList.Next != null)
        {
            pagingList = await api.GetNextPageAsync(pagingList);

            returnList.AddRange(pagingList.Items);
        }
        return(returnList);
    }
        private void authResponseReceivedEvent(Models.Token token, string state)
        {
            mAuth.StopHttpServer();
            mSpotify = new SpotifyWebAPI();
            if (state != "XSS")
            {
                mErrorMessage = "Wrong state received.";
                return;
            }
            if (token.Error != null)
            {
                mErrorMessage = token.Error;
                return;
            }

            mSpotify.UseAuth     = true;
            mSpotify.AccessToken = token.AccessToken;
            mSpotify.TokenType   = token.TokenType;
            mProfile             = mSpotify.GetPrivateProfile();
        }
    public static async Task <List <Playlist> > ConvertSimplePlaylist(List <SAPIModels.SimplePlaylist> playlistList, bool getTracks, SpotifyAPI.Web.SpotifyWebAPI api, string userId)
    {
        List <Playlist> playlists = new List <Playlist>();

        foreach (SAPIModels.SimplePlaylist p in playlistList)
        {
            List <Track> ts = null;
            if (getTracks)
            {
                List <SAPIModels.PlaylistTrack> tracks = null;
                if (api != null && !string.IsNullOrEmpty(userId))
                {
                    SAPIModels.Paging <SAPIModels.PlaylistTrack> currentTracks = await api.GetPlaylistTracksAsync(userId, p.Id, "", 100);

                    tracks = await GetAllFromPagingAsync(api, currentTracks);
                }

                try
                {
                    ts = tracks?.Select(x => new Track(x.Track)).ToList();
                }
                catch (Exception e)
                {
                    Analysis.LogError($"Service Playlist Track Error on '{p.Name}' - {e}", Analysis.LogLevel.Vital);
                }
            }

            playlists.Add(new Playlist()
            {
                Name     = p.Name,
                Uri      = p.Uri,
                Tracks   = ts,
                ImageUrl = p.Images != null && p.Images.Count > 0 ? p.Images.FirstOrDefault().Url : null,
                Author   = string.IsNullOrEmpty(p.Owner.DisplayName) ? p.Owner.Id : p.Owner.DisplayName,
            });
        }
        return(playlists);
    }