public override void Disable()
 {
     _spotify     = null;
     _trackId     = null;
     _contextId   = null;
     _albumArtUrl = null;
 }
Exemplo n.º 2
0
        private async Task HandleArtirst(SpotifyClient client, DisplayCard displayCard, string itemId)
        {
            var artist = await GetArtist(client, itemId);

            displayCard.ContextName  = artist.Name;
            displayCard.ContextImage = artist.Images.FirstOrDefault().Url;
        }
        protected async Task <List <string> > GetTopArtistIds(string accessToken)
        {
            Logger.LogInformation("Getting top artists...");

            try
            {
                //Initialise the SpotifyClient with the access token provided by the user authenticating with Spotify
                var api = new SpotifyClient(accessToken);

                var topArtistIds = new List <string>();

                var response = await api.Personalization.GetTopArtists(new PersonalizationTopRequest
                {
                    TimeRangeParam = PersonalizationTopRequest.TimeRange.LongTerm,
                    Limit          = SpotifyConsts.MaxLimitGetTopArtists
                });

                topArtistIds.AddRange(response.Items.Select(artistItem => artistItem.Id));

                Logger.LogInformation("Returning {0} top artists.", topArtistIds.Count);
                return(topArtistIds);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "");
                //Not an essential method, just return empty
                return(new List <string>());
            }
        }
        /// <summary>
        /// Attempt to get the user's email address. If this fails for any reason, it's not critical - it just
        /// means we have to validate the email address before sending any other emails
        /// </summary>
        public async Task <GetUserEmailOutput> GetUserEmail(GetUserEmailInput input)
        {
            Logger.LogInformation("Getting user email...");

            try
            {
                //Initialise the SpotifyClient with the access token provided by the user authenticating with Spotify
                var api = new SpotifyClient(input.AccessToken);

                var response = await api.UserProfile.Current();

                //Don't actually log their email address, for privacy/security reasons
                Logger.LogInformation("Returning user email...");

                return(new GetUserEmailOutput
                {
                    EmailAddress = response.Email
                });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "");
                return(new GetUserEmailOutput
                {
                    ErrorMessage = ex.Message
                });
            }
        }
Exemplo n.º 5
0
        public static async Task <SimplePlaylist> getPlayListById(string id)
        {
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current();


            var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false));

            SimplePlaylist item = null;

            foreach (SimplePlaylist list_item in playlists)
            {
                if (list_item.Id == id)
                {
                    item = list_item;
                    break;
                }
            }

            _server.Dispose();

            return(item);
        }
Exemplo n.º 6
0
        public static async Task setVolume(int volume)
        {
            if (Mute)
            {
                await Desmute();
            }
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current();

            //   Debug.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!");
            int atualpercent = spotify.Player.GetCurrentPlayback().Result.Device.VolumePercent.GetValueOrDefault();
            int result       = atualpercent + volume;
            PlayerVolumeRequest playvolumecontext = new PlayerVolumeRequest(result);

            await spotify.Player.SetVolume(playvolumecontext);


            _server.Dispose();
            //  Environment.Exit(0);
        }
Exemplo n.º 7
0
 public AtlasHierarchy(SpotifyClient client, AtlasViewOptions viewOptions)
 {
     Client = client;
     NodeDictionary = new Dictionary<String, IHierarchyNode>();
     RootNodes = new List<IHierarchyNode>();
     AddChildrenLimit = viewOptions.AddChildrenCount;
 }
Exemplo n.º 8
0
        public static async Task Desmute()
        {
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current();

            //   Debug.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!");

            PlayerVolumeRequest playvolumecontext = new PlayerVolumeRequest(volumeBefore);

            await spotify.Player.SetVolume(playvolumecontext);

            Mute = false;

            _server.Dispose();
        }
Exemplo n.º 9
0
        public async Task <UserInformation> FinishLogIn(SpotifyCode spotifyCode)
        {
            var response = await new OAuthClient()
                           .RequestToken(new AuthorizationCodeTokenRequest(_spotifyService.ClientID, _spotifyService.ClientSecret, spotifyCode.Code, _spotifyService.RedirectUri));
            var spotify = new SpotifyClient(response.AccessToken);
            var user    = await spotify.UserProfile.Current();

            var userInformation = new UserInformation(user.DisplayName, user.Id, response.AccessToken);

            // save refresh token to DB
            try
            {
                var token = await _context.RefreshTokens.FirstOrDefaultAsync(t => t.UserID == user.Id);

                if (token != null)
                {
                    token.Token = response.RefreshToken;
                }
                else
                {
                    var refreshToken = new RefreshToken(user.Id, response.RefreshToken);
                    await _context.RefreshTokens.AddAsync(refreshToken);
                }
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            return(userInformation);
        }
Exemplo n.º 10
0
        public async Task Login(string code)
        {
            var(accessToken, refreshToken) = await SpotifyClient.GetTokensAsync(ClientId, ClientSecret, RedirectUrl, code).ConfigureAwait(false);

            AccessToken  = accessToken;
            RefreshToken = refreshToken;
        }
Exemplo n.º 11
0
        private async Task RefreshTokenAsync(string refreshToken)
        {
            try
            {
                // await File.WriteAllTextAsync("code.txt", code);
                var response = await new OAuthClient().RequestToken(
                    new AuthorizationCodeRefreshRequest(spotifyConfig.ClientId, spotifyConfig.ClientSecret, refreshToken)
                    );

                var config = SpotifyClientConfig
                             .CreateDefault()
                             .WithAuthenticator(new AuthorizationCodeAuthenticator(spotifyConfig.ClientId,
                                                                                   spotifyConfig.ClientSecret, new AuthorizationCodeTokenResponse()
                {
                    AccessToken  = response.AccessToken,
                    ExpiresIn    = response.ExpiresIn,
                    RefreshToken = refreshToken,
                    CreatedAt    = response.CreatedAt,
                    Scope        = response.Scope,
                    TokenType    = response.TokenType
                }));

                spotifyClient = new SpotifyClient(config);
                IsAuthed      = true;
            }
            catch (Exception ex)
            {
                // TODO: figure out what might lead here
                return;
            }
        }
Exemplo n.º 12
0
        static async Task Main(string[] args)
        {
            try
            {
                var token = await SpotifyClient.GetAccessToken(CLIENT_ID, CLIENT_SECRET);

                try
                {
                    var client = new SpotifyClient(token);

                    var searchResponse = await client.Search("Coheed & Cambria", new string[] { "track" });

                    foreach (var track in searchResponse.Tracks.Items)
                    {
                        Console.WriteLine(track.Name);
                    }
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"Error while executing API request: {e.Message}");
                }
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Error while authenticating: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Uncaught error: {e}");
            }

            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 13
0
        public async Task <bool> SwapCodeForTokenAsync(string code)
        {
            try
            {
                // await File.WriteAllTextAsync("code.txt", code);
                var response = await new OAuthClient().RequestToken(
                    new AuthorizationCodeTokenRequest(spotifyConfig.ClientId, spotifyConfig.ClientSecret, code,
                                                      new Uri("https://localhost:5001/callback"))
                    );

                await File.WriteAllTextAsync("refresh.txt", response.RefreshToken);

                var config = SpotifyClientConfig
                             .CreateDefault()
                             .WithAuthenticator(new AuthorizationCodeAuthenticator(spotifyConfig.ClientId,
                                                                                   spotifyConfig.ClientSecret, response));

                spotifyClient = new SpotifyClient(config);
                IsAuthed      = true;

                return(true);
            }
            catch (Exception ex)
            {
                // TODO: figure out what might lead here
                return(false);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Checks if user is authenticated
        /// </summary>
        /// <returns>
        /// Null if failed, Profile if successful
        /// </returns>
        public static async Task <PrivateUser> IsAuthenticated()
        {
            //check if file with token exists, if it does not exist, login will be shown
            if (!File.Exists(CredentialsPath))
            {
                return(null);
            }

            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <AuthorizationCodeTokenResponse>(json);

            CheckCliendSecretId();

            if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
            {
                return(null);
            }

            var authenticator = new AuthorizationCodeAuthenticator(clientId, clientSecret, token);

            authenticator.TokenRefreshed += (sender, tokenx) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(tokenx));

            //might throw an error if user revoked access to their spotify account
            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            SpotifyClient = new SpotifyClient(config);
            //try and get user profile
            return(await SpotifyClient.UserProfile.Current());
        }
Exemplo n.º 15
0
        private async Task HandleAlbum(SpotifyClient client, DisplayCard displayCard, string itemId)
        {
            var album = await GetAlbum(client, itemId);

            displayCard.ContextName  = album.Name;
            displayCard.ContextImage = album.Images.FirstOrDefault().Url;
        }
Exemplo n.º 16
0
        private async Task LoginToSpotify(TaskCompletionSource <bool> tcs)
        {
            Server = new EmbedIOAuthServer(new Uri("http://localhost:5000/callback"), 5000);
            await Server.Start();

            Server.ImplictGrantReceived += async(object sender, ImplictGrantResponse response) =>
            {
                await Server.Stop();

                if (response.AccessToken != null)
                {
                    Spotify = new SpotifyClient(response.AccessToken);
                    Profile = await Spotify.UserProfile.Current();

                    tcs.SetResult(Spotify != null);
                }
                else
                {
                    Log("Error when attempting to log in");
                    tcs.SetResult(false);
                }
            };

            var request = new LoginRequest(Server.BaseUri, SpotifySecrets.CLIENT_ID, LoginRequest.ResponseType.Token)
            {
                Scope = new List <string>
                {
                    Scopes.UserLibraryRead,
                    Scopes.PlaylistModifyPublic
                }
            };

            BrowserUtil.Open(request.ToUri());
        }
Exemplo n.º 17
0
        public override async Task <SkillResponse> HandleIntent(SkillRequest skillRequest, IntentRequest intentRequest,
                                                                ILambdaContext context)
        {
            await SpotifyClient.SkipPlaybackToNextAsync();

            return(ReturnEmptySkillResponse());
        }
Exemplo n.º 18
0
        private void Start()
        {
            Log.Instance.PrintMessage("Trying to connect to Spotify...", MessageType.Info, "Spotify.Start()");
            User = null;
            Stopwatch crono = Stopwatch.StartNew();

            Kernel.InternetAvaliable(false);
            try
            {
                SpotifyConfig = SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(PublicKey, PrivateKey));
                SpotifyClient = new SpotifyClient(SpotifyConfig);
                crono.Stop();
                if (SpotifyConfig is not null) //??
                {
                    Kernel.InternetAvaliable(true);
                    Log.Instance.PrintMessage("Connected!", MessageType.Correct, crono, TimeType.Milliseconds);
                }
                else //yo  creoque esto nunca se ejecuta...
                {
                    Kernel.InternetAvaliable(false);
                    Log.Instance.PrintMessage("Token is null", MessageType.Error, crono, TimeType.Milliseconds);
                }
            }
            catch (APIException ex)
            {
                Kernel.InternetAvaliable(false);
                Log.Instance.PrintMessage(ex.Message, MessageType.Error);
                MessageBox.Show(Kernel.LocalTexts.GetString("error_internet"));
            }
        }
Exemplo n.º 19
0
        public static async Task Run(
            //[TimerTrigger("0 * * * * *")] TimerInfo timer,
            [TimerTrigger("0 0 0 1 * *")] TimerInfo timer,
            [Table("chainLinks", Connection = "AzureWebJobsStorage")] CloudTable chainLinksCloudTable,
            ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            log.LogInformation("Getting chain links...");

            var lastMonthsChainLinks = (await new ChainLinkRepository(chainLinksCloudTable)
                                        .GetAll())
                                       .GetLastMonthsChainLinks(DateTime.Today);

            log.LogInformation($"Got chain links {lastMonthsChainLinks.Min(l => l.Position)} to {lastMonthsChainLinks.Max(l => l.Position)}.");

            var client = new SpotifyClient(
                new SpotifyConfiguration(
                    GetEnvironmentVariable("SpotifyClientId"),
                    GetEnvironmentVariable("SpotifyClientSecret"),
                    GetEnvironmentVariable("SpotifyRefreshToken")),
                log);

            await client.RefreshPlaylist(lastMonthsChainLinks,
                                         new SpotifyPlaylist(
                                             new Uri(GetEnvironmentVariable("SpotifyPlaylistUri")),
                                             "The Chain Monthly", true, false,
                                             $"{DateTime.Today.AddMonths(-1):MMMM} in The Chain, BBC Radio 6's listener-generated playlist of thematically linked songs. Check https://www.thechain.uk/ for more."
                                             ));
        }
Exemplo n.º 20
0
    protected override void OnSpotifyConnectionChanged(SpotifyClient client)
    {
        base.OnSpotifyConnectionChanged(client);

        _client = client;

        // Start internal update loop
        if (_client != null && UpdateFrequencyMS > 0)
        {
            if (SpotifyService.Instance.AreScopesAuthorized(Scopes.UserReadPlaybackState))
            {
                InvokeRepeating(nameof(FetchLatestPlayer), 0, UpdateFrequencyMS / 1000);
                _isInvoking = true;
            }
            else
            {
                Debug.LogError($"Not authorized to access '{Scopes.UserReadPlaybackState}'");
            }
        }
        else if (_client == null && _isInvoking)
        {
            CancelInvoke(nameof(FetchLatestPlayer));
            _isInvoking = false;

            // Invoke playing item changed, no more client, no more context
            OnPlayingItemChanged?.Invoke(null);
        }
    }
Exemplo n.º 21
0
        //public Album()
        //      {
        //	tracks = new List<Track>();
        //      }
        public void GetTracks(SpotifyClient client)
        {
            var responseA = client.Albums.GetTracks(id).Result;

            var trackIds = client.Albums.GetTracks(id).Result.Items.Select(t => t.Id).ToList();

            for (int i = 0; i < trackIds.Count; i += (trackIds.Count - i) >= 50 ? 50 : (trackIds.Count - i))
            {
                var request  = new TracksRequest(trackIds.GetRange(i, ((trackIds.Count - i) >= 50 ? 50 : (trackIds.Count - i))));
                var response = client.Tracks.GetSeveral(request).Result.Tracks;
                response.ForEach(t =>
                {
                    var track = new Track()
                    {
                        duration_ms  = t.DurationMs,
                        isexplicit   = t.Explicit,
                        name         = t.Name,
                        popularity   = t.Popularity,
                        preview_url  = t.PreviewUrl,
                        track_number = t.TrackNumber,
                        type         = t.Type.ToString(),
                        uri          = t.Uri,
                        spotify_url  = t.ExternalUrls.Values.FirstOrDefault(),
                        id           = t.Id,
                        disc_number  = t.DiscNumber
                    };
                    tracks.Add(track);
                });
            }
            ;
        }
        public async Task <FullPlaylist> CreatePlaylistFromArtists(
            IEnumerable <string> artistNames, string playlistName, string accessToken)
        {
            var spotifyClient = new SpotifyClient(accessToken);

            var tracks = new List <FullTrack>();

            foreach (var artistName in artistNames)
            {
                var searchResponse = await spotifyClient.Search.Item(new SearchRequest(SearchRequest.Types.Track, $"artist:{artistName}"));

                tracks.AddRange(searchResponse.Tracks.Items !.Take(10));
            }

            var currentUser = await spotifyClient.UserProfile.Current();

            var playlist = await spotifyClient.Playlists.Create(currentUser.Id, new PlaylistCreateRequest(playlistName));

            foreach (var tracksChunk in tracks.Shuffle().Chunk(100))
            {
                await spotifyClient.Playlists.AddItems(playlist.Id !,
                                                       new PlaylistAddItemsRequest(tracksChunk.Select(x => x.Uri).ToList()));
            }

            return(playlist);
        }
Exemplo n.º 23
0
        private async Task <string?> GetSpotifyTrack(string link)
        {
            var spotifyConfig = SpotifyClientConfig
                                .CreateDefault()
                                .WithAuthenticator(
                new ClientCredentialsAuthenticator(config["SpotifyId"], config["SpotifySecret"]));

            var spotify = new SpotifyClient(spotifyConfig);

            var id = link.Split("/").LastOrDefault();
            var idWithoutQueryString = id?.Split("?").FirstOrDefault();

            if (idWithoutQueryString != null)
            {
                id = idWithoutQueryString;
            }

            var track = await spotify.Tracks.Get(id ?? "");

            string?result = null;

            if (track != null)
            {
                result = "";
                foreach (var artist in track.Artists)
                {
                    result += artist.Name + " ";
                }

                result += " " + track.Name;
            }

            return(result);
        }
Exemplo n.º 24
0
        public static async Task PlayPlaylist(SimplePlaylist playlist)
        {
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current();



            PlayerResumePlaybackRequest teste = new PlayerResumePlaybackRequest();

            teste.ContextUri = playlist.Uri;

            await spotify.Player.ResumePlayback(teste);


            _server.Dispose();
            //  Environment.Exit(0);
        }
Exemplo n.º 25
0
        public override async Task <SkillResponse> HandleIntent(SkillRequest skillRequest, IntentRequest intentRequest,
                                                                ILambdaContext context)
        {
            var profile = await SpotifyClient.GetPrivateProfileAsync();

            if (profile.HasError())
            {
                return(TellWithoutEnding("There was an error getting your profile"));
            }

            var playlists = await SpotifyClient.GetUserPlaylistsAsync(profile.Id);

            if (playlists.HasError())
            {
                return(TellWithoutEnding("There was an error getting your playlists"));
            }

            var playlistName = intentRequest.GetSlotValue("PlaylistName");
            var list         = (from playlist in playlists.Items
                                let score = new SmithWatermanGotoh().GetSimilarity(playlist.Name.ToLower(), playlistName.ToLower())
                                            select new MostMatchingPlaylist(playlist, score)).ToList();

            var mostMatching = list.MaxBy(x => x.Score).FirstOrDefault();

            if (mostMatching == null)
            {
                return(TellWithoutEnding("Sorry. Couldn't find the requested playlist"));
            }

            var speech = $"Found {mostMatching.Playlist.Name}, is this the correct one?";

            skillRequest.Session.SetSessionValue("PlaylistUri", mostMatching.Playlist.Uri);
            return(ResponseBuilder.Ask(speech, new Reprompt(speech), skillRequest.Session));
        }
Exemplo n.º 26
0
        public static async Task <System.Collections.Generic.IList <SpotifyAPI.Web.SimplePlaylist> > getAllPlayerList()
        {
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current();


            var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false));

            _server.Dispose();

            return(playlists);


            //  Environment.Exit(0);
        }
Exemplo n.º 27
0
    public async void SetPlaylist(SimplePlaylist playlist)
    {
        _playlist = playlist;

        // Add loading spinner on main thread
        if (_loadSpinnerPrefab != null)
        {
            _dispatcher.Add(() =>
            {
                _instLoadSpinner = Instantiate(_loadSpinnerPrefab, _tracksListParent);
            });
        }

        SpotifyClient client = SpotifyService.Instance.GetSpotifyClient();

        // Get full details of simple playlist
        _fullPlaylist = await client.Playlists.Get(_playlist.Id);

        // Get all tracks inside full playlist
        _allTracks = await GetAllTracks(client);

        // Require ui update on main thread
        _dispatcher.Add(() =>
        {
            UpdateUI();

            if (_instLoadSpinner != null)
            {
                Destroy(_instLoadSpinner);
            }
        });
    }
Exemplo n.º 28
0
        public override async Task <SkillResponse> HandleIntent(SkillRequest skillRequest, IntentRequest intentRequest,
                                                                ILambdaContext context)
        {
            await SpotifyClient.ResumePlaybackAsync(offset : "");

            return(ReturnEmptySkillResponse());
        }
Exemplo n.º 29
0
        private static async Task Start()
        {
            var json = await File.ReadAllTextAsync(CredentialsPath);

            var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json);

            var authenticator = new PKCEAuthenticator(clientId !, token);

            authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));

            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(authenticator);

            var spotify = new SpotifyClient(config);

            var me = await spotify.UserProfile.Current();

            Console.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!");

            var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false));

            Console.WriteLine($"Total Playlists in your Account: {playlists.Count}");

            _server.Dispose();
            Environment.Exit(0);
        }
Exemplo n.º 30
0
        public async Task <ActionResult> PauseCurrentTrack()
        {
            try
            {
                var tokenGiven = _cookiesManager.GetCookie("TokenGiven", Request);
                var tokenTimes = _cookiesManager.GetCookie("TokenTime", Request);

                if (tokenGiven != null && tokenTimes != null)
                {
                    if (ApiClientConfig.IsIfTokenExpired(Convert.ToDateTime(tokenTimes.Value), tokenGiven.Value))
                    {
                        return(RedirectToAction("LoginUser"));
                    }
                }
                else
                {
                    return(RedirectToAction("LoginUser"));
                }

                client = ApiClientConfig.GetClientInstance(tokenGiven.Value);

                var tryPauseTrack = await _playerRepo.PauseCurrentPlayBack(client);

                var modelValues = await GetPrivateUserDefaultModel(client);

                _model = modelValues;

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return(View(ERROR_MESSAGE_PATH)); throw;
            }
        }
Exemplo n.º 31
0
        public SpotifyClientService()
        {
            var config = SpotifyClientConfig.CreateDefault()
                         .WithAuthenticator(new ClientCredentialsAuthenticator(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET));

            _spotify = new SpotifyClient(config);
        }
Exemplo n.º 32
0
        public ArtistAtlasHierarchy(SpotifyClient client, IEnumerable<Artist> artists, AtlasViewOptions viewOptions)
            : base(client, viewOptions) {

            foreach (Artist artist in artists)
            {
                GenerateTree(artist);
            }
        }
Exemplo n.º 33
0
        public Artist Recommend(SpotifyClient client, Playlist playlist)
        {
            //Find a common ancestor for a portion of the artists in the playlist.
            IEnumerable<Track> playlistEntries = playlist.Tracks.Select(track => track.Track);

            Dictionary<string, ArtistGroup> cachedRelatedArtists = new Dictionary<string, ArtistGroup>();

            Dictionary<string, RecommendationCriteria> relatedArtistMap = new Dictionary<string, RecommendationCriteria>();
            playlistEntries.ToList().ForEach(track =>
            {
                ArtistGroup relatedArtists = null;
                if (!cachedRelatedArtists.ContainsKey(track.Artists.First().ID))
                {
                    relatedArtists = client.GetRelatedArtists(track.Artists.First().ID); //Handle only the first artist for now...
                    cachedRelatedArtists.Add(track.Artists.First().ID, relatedArtists);
                }
                else
                {
                    relatedArtists = cachedRelatedArtists[track.Artists.First().ID];
                }

                relatedArtists.Artists.ForEach(relatedArtist =>
                {
                    if (!relatedArtistMap.ContainsKey(relatedArtist.ID))
                    {
                        RecommendationCriteria recommendationCriteria = new RecommendationCriteria();
                        relatedArtistMap.Add(relatedArtist.ID, recommendationCriteria);
                        recommendationCriteria.TargetedArtist = relatedArtist;
                    }

                    if (!relatedArtistMap[relatedArtist.ID].RelatedArtists.Where(artist => artist.ID == track.Artists.First().ID).Any())
                        relatedArtistMap[relatedArtist.ID].RelatedArtists.Add(track.Artists.First());

                    relatedArtistMap[relatedArtist.ID].Weight++;
                });
            });

            //Other ideas:
            //Recommend by the playlist contents.
            //  Evaluate whether the playlist is a collection of like-artists or individual songs of a particular type (e.g. energetic, fast?)
            //Recommend by the artist selected.
            //
            //Recommend something completely new.  
            //Recommend a set of brand-new songs.
            //  Analyze all changelists to get an idea of what a person likes in particular.  
            //  Easily solution is to find artists that they don't have that are similar.
            //  Could also randomly find songs from various areas:
            //      The current Top 10-40 on the charts.
            //      The list of a band that is playing near you live.
            //      Find a whole smattering of a different genre (trip hop, hip hop, grunge alternative).
            //Recommend by a specific song.
            //      Find songs that were popular at the same time (may not need to be part of the same genre).

            IOrderedEnumerable<KeyValuePair<string, RecommendationCriteria>> orderedDictionary = relatedArtistMap.OrderByDescending(keyValuePair => keyValuePair.Value.Weight)
                                                                                                                    .ThenByDescending(keyValuePair => keyValuePair.Value.RelatedArtists.Count());
            KeyValuePair<string, RecommendationCriteria> recommendedEntry = orderedDictionary.First();
            return recommendedEntry.Value.TargetedArtist;
        }
        public void SpotifyClient_GetPlaylists()
        {
            SpotifyClient client = new SpotifyClient(creds);
            SpotifyPlaylistsResponse response = null;
            if(client.Connected)
                response = client.GET<SpotifyPlaylistsResponse>(new SpotifyPlaylistsRequest());

            Assert.AreNotEqual(null, response);
        }
Exemplo n.º 35
0
        public PlaylistViewModel()
        {
            _playlist = null;
            _client = SpotifyClientService.Client;

            _showTutorialInfo = true;
            _playlists = _client.GetPlaylists(SpotifyClientService.User.Id);

            _displayPlaylists = _playlists.Playlists;
            _displayPlaylists.Insert(0, new Playlist("New Playlist"));
        }
Exemplo n.º 36
0
        public AtlasHierarchy(SpotifyClient client, IEnumerable<String> artistNames)
        {
            Client = client;
            NodeDictionary = new Dictionary<String, HierarchyNode>();
            RootNodes = new List<HierarchyNode>();
            MaxChildren = 1;

            foreach (String artistName in artistNames)
            {
                GenerateTree(artistName);
            }
        }
        public void SpotifyClient_GetTracksForPlaylist()
        {
            SpotifyClient client = new SpotifyClient(creds);
            SpotifyPlaylist playlist = null;
            SpotifyPlaylistTracksRequest tracksRequest = null;
            SpotifyPlaylistTracksResponse tracksResponse = null;
            if (client.Connected)
            {
                playlist = client.GET<SpotifyPlaylistsResponse>(new SpotifyPlaylistsRequest()).Items.FirstOrDefault();
                tracksRequest = new SpotifyPlaylistTracksRequest()
                {
                    Playlist_ID = playlist.ID
                };

                tracksResponse = client.GET<SpotifyPlaylistTracksResponse>(tracksRequest);
                Console.WriteLine("test");
            }
        }
Exemplo n.º 38
0
        static int Main(string[] args)
        {
            ClientInterface cli;
            string searchQuery;
            SpotifyClient.RequestType rt;

            if (args.Length < 2)
            {
                return 0;
            }
            MyOptions options = new MyOptions(args);
            searchQuery = options.getParameter(Params.QUERY);

            if (options.getParameter(Params.CLIENT).Equals("spotify"))
            {
                rt = options.getParameter(Params.TRACK_OR_ARTIST).Equals("artist") ? SpotifyClient.RequestType.Artist : SpotifyClient.RequestType.Track;
                cli = new SpotifyClient(rt, searchQuery, 300);
            }
            else if (options.getParameter(Params.CLIENT).Equals("soundcloud"))
            {
                cli = new SoundCloudClient(searchQuery);
            }
            else
            {
                return 1;
            }

            if (cli.Search())
            {
                cli.GetImages();
                cli.DownloadImage();
            }

            return 0;
        }
Exemplo n.º 39
0
 static SpotifyClientService()
 {
     Client = new SpotifyClient();
     Country = "US"; //TODO:  Determine the user's current market.
 }
Exemplo n.º 40
0
 public SpotiFireService(IMapEngine mapEngine, IPlaylistHolder playlistHolder)
 {
     _mapEngine = mapEngine;
     _spotiFire = new SpotifyClient();
     _playlistHolder = playlistHolder;
 }
 public NewReleaseAtlasHierarchy(SpotifyClient client, IEnumerable<NewReleaseItem> newReleases, AtlasViewOptions viewOptions)
     : base(client, viewOptions) {
     foreach (NewReleaseItem newReleaseItem in newReleases) {
         GenerateTree(newReleaseItem);
     }
 }
 public void SpotifyClient_Connect()
 {
     SpotifyClient client = new SpotifyClient(creds);
     Assert.AreEqual(true, client.Connected);
 }