Пример #1
0
    public IEnumerator LoadRecentlyPlayed()
    {
        yield return(new WaitForSeconds(2));

        recentlyPlayed = spotifyManagerScript.GetRecentlyPlayed();

        if (recentlyPlayed == null || recentlyPlayed.Items.Count == 0)
        {
            Debug.LogError("recentlyPlayed is null/empty");
        }
        else
        {
            for (int i = 0; i < meshRenderers.Length; i++)
            {
                FullTrack fullTrack = spotifyManagerScript.GetTrack(recentlyPlayed.Items[i].Track.Id);

                string recentlyPlayedImageURL = null;

                if (fullTrack.Album.Images.Count != 0)
                {
                    recentlyPlayedImageURL = fullTrack.Album.Images[0].Url;
                }

                GameObject meshRendererGameObject = meshRenderers[i].transform.gameObject;

                PlaylistScript playlistScript = meshRendererGameObject.GetComponent <PlaylistScript>();

                WWW imageURLWWW = null;

                if (recentlyPlayedImageURL != null)
                {
                    imageURLWWW = new WWW(recentlyPlayedImageURL);

                    yield return(imageURLWWW);

                    meshRenderers[i].material.mainTexture = imageURLWWW.texture;
                }


                AudioAnalysis audioAnalysis = spotifyManagerScript.GetAudioAnalysis(recentlyPlayed.Items[i].Track.Id);

                playlistScript.setPlaylistName(recentlyPlayed.Items[i].Track.Name);
                playlistScript.trackType = PlaylistScript.TrackType.track;
                playlistScript.setPlaylistURI(recentlyPlayed.Items[i].Track.Uri);
                playlistScript.artistId      = recentlyPlayed.Items[i].Track.Artists[0].Id;
                playlistScript.trackId       = recentlyPlayed.Items[i].Track.Id;
                playlistScript.audioAnalysis = audioAnalysis;

                if (imageURLWWW != null)
                {
                    playlistScript.www    = imageURLWWW;
                    playlistScript.sprite = Converter.ConvertWWWToSprite(imageURLWWW);
                    saveLoad.SaveTextureToFilePNG(Converter.ConvertWWWToTexture(imageURLWWW), "recentlyPlayed" + i + ".png");
                }

                playlistScript.audioAnalysisCustom = new AudioAnalysisCustom(audioAnalysis);
                saveLoad.savedRecentlyPlayed.Add(new PlaylistScriptData(playlistScript));
            }
        }
    }
Пример #2
0
        public async Task <CursorPaging <DTO.PlayHistoryItem> > GetRecentlyPlayed([FromQuery] long?after = null)
        {
            await Task.Delay(0);

            var musicHistory = context.PlayHistoryItems;
            List <DTO.PlayHistoryItem> listOfRecentlyPlayed = new List <DTO.PlayHistoryItem>();

            if (after == null)
            {
                foreach (var item in musicHistory)
                {
                    listOfRecentlyPlayed.Add(item.ToDTO());
                }
            }
            else
            {
                var afterAsDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                afterAsDateTime = afterAsDateTime.AddMilliseconds((double)after);
                foreach (var item in musicHistory)
                {
                    if (item.PlayedAt >= afterAsDateTime)
                    {
                        listOfRecentlyPlayed.Add(item.ToDTO());
                    }
                }
            }

            var listeningHistory = new CursorPaging <DTO.PlayHistoryItem>
            {
                Items = listOfRecentlyPlayed
            };

            return(listeningHistory);
        }
 public static IEnumerable <ExtendedPlayHistory> ConvertToExtendedPlayHistory(CursorPaging <PlayHistory> history)
 {
     foreach (var page in history.Items)
     {
         yield return(PropertyCopy <ExtendedPlayHistory> .CopyFrom(page));
     }
 }
        public static void Scheduler_Elapsed(SpotifyWebAPI api)
        {
            long     previousTimeStamp            = FileManager.GetMostRecentTimeStamp();
            DateTime timeStamp                    = DateTimeOffset.FromUnixTimeMilliseconds(previousTimeStamp).UtcDateTime;
            CursorPaging <PlayHistory> recentData = api.GetUsersRecentlyPlayedTracks(50, timeStamp);

            RecordSongs(recentData, api);
        }
Пример #5
0
        public void ModifyPlayback()
        {
            //See if they're already listening to music.
            if (m_spotifyWebAPI.GetPlayingTrack().IsPlaying)
            {
                //Already listening to music, we'll modify and pause it
                ErrorResponse e = m_spotifyWebAPI.PausePlayback();

                if (e.HasError())
                {
                    Console.WriteLine(e.Error.Message);
                }
            }
            else
            {
                //Not currently listening, so let's get it resumed
                //Get their last played track
                CursorPaging <PlayHistory> history = m_spotifyWebAPI.GetUsersRecentlyPlayedTracks();
                if (history.HasError())
                {
                    Console.WriteLine(history.Error.ToString());
                }
                else if (history.Items.Count > 0)
                {
                    //By not setting any variables, we continue playback from the last playlist, with the
                    //last song listened to.
                    ErrorResponse e = m_spotifyWebAPI.ResumePlayback("", "", null, "", 0);
                    if (e.HasError())
                    {
                        Console.WriteLine(e.Error.Message);

                        if (e.Error.Status == 404)
                        {
                            List <Device> devices = m_spotifyWebAPI.GetDevices().Devices;

                            for (int i = 0; i < devices.Count; i++)
                            {
                                if (devices[i].IsRestricted == false)
                                {
                                    m_spotifyWebAPI.ResumePlayback(devices[i].Id, "", null, "", 0);
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        //Let whatever wants to know that the song has 'changed'.
                        //Because technically it hasn't, our polling method won't pick this up.
                        //But anything wanting to know about this, won't be told there's a song playing
                        //so we'll trigger this ourself.
                        FullTrack lastSong = m_spotifyWebAPI.GetPlayingTrack().Item;
                        m_instance.m_onSongChanged.Invoke(lastSong);
                    }
                }
            }
        }
        /// <inheritdoc/>
        public async Task <JsonResult> GetSpotifyRecentlyPlayed(SpotifyAuthenticationToken authToken, long?after = null)
        {
            await Task.Delay(0);

            var requesturiString    = string.Format("http://localhost:2222/v1/me/player/recently-played?after={0}", after);
            var musicHistory        = externalAPICaller.Get <CursorPaging <FakeResponseServer.DTO.PlayHistoryItem> >(new Uri(requesturiString));
            var correctMusicHistory = new CursorPaging <PlayHistoryItem>
            {
                Items = new List <PlayHistoryItem>()
            };

            foreach (var item in musicHistory.Items)
            {
                correctMusicHistory.Items.Add(new PlayHistoryItem
                {
                    Context = new Context
                    {
                        ExternalUrls = new Dictionary <string, string>(),
                        Href         = item.Context.Href,
                        Type         = item.Context.Type,
                        Uri          = item.Context.Uri
                    },
                    PlayedAt = (DateTime)item.PlayedAt,
                    Track    = new SimpleTrack
                    {
                        Artists          = new List <SimpleArtist>(),
                        AvailableMarkets = new List <string>(),
                        DiscNumber       = item.Track.DiscNumber,
                        DurationMs       = item.Track.DurationMs,
                        Explicit         = item.Track.Explicit,
                        ExternalUrls     = new Dictionary <string, string>(),
                        Href             = item.Track.Href,
                        Id         = item.Track.Id,
                        IsPlayable = item.Track.IsPlayable,
                        LinkedFrom = new LinkedTrack
                        {
                            ExternalUrls = new Dictionary <string, string>(),
                            Href         = item.Track.LinkedFrom.Href,
                            Id           = item.Track.LinkedFrom.Id,
                            Type         = item.Track.LinkedFrom.Type,
                            Uri          = item.Track.LinkedFrom.Uri,
                        },
                        Name        = item.Track.Name,
                        PreviewUrl  = item.Track.PreviewUrl,
                        TrackNumber = item.Track.TrackNumber,
                        Type        = ItemType.Track,
                        Uri         = item.Track.Uri
                    }
                });;
            }
            return(new JsonResult(correctMusicHistory));
        }
Пример #7
0
        private IEnumerable <SimplePlaylist> GetPlaylist(CursorPaging <PlayHistory> ob)
        {
            try
            {
                IEnumerable <PlayHistory> obj = ob.Items.GroupBy(x => x.Track.Name)
                                                .Select(g => g.First())
                                                .ToList();

                List <SimplePlaylist> list = new List <SimplePlaylist>();
                foreach (var t in obj)
                {
                    Tuple <ResponseInfo, string> tuple1;
                    if (t.Track.Album.Type == "album" || t.Context.Type == "album")
                    {
                        tuple1 = client.Download(builder.GetAlbum(t.Track.Album.Uri.Substring(14)), headers);
                        var obj1 = JsonConvert.DeserializeObject <FullAlbum>(tuple1.Item2);
                        list.Add(new SimplePlaylist()
                        {
                            Name = obj1.Name, Id = obj1.Id, Images = obj1.Images, Type = obj1.Type, Tracks = new PlaylistTrackCollection()
                            {
                                Total = obj1.Tracks.Total
                            }
                        });
                    }
                    else if (t.Context.Type == "playlist")
                    {
                        tuple1 = client.Download(builder.GetPlaylist(t.Track.Album.Uri.Substring(17)), headers);
                        var obj2 = JsonConvert.DeserializeObject <FullPlaylist>(tuple1.Item2);
                        list.Add(new SimplePlaylist()
                        {
                            Name = obj2.Name, Id = obj2.Id, Images = obj2.Images, Type = obj2.Type, Owner = obj2.Owner, Tracks = new PlaylistTrackCollection()
                            {
                                Total = obj2.Tracks.Total
                            }
                        });
                    }
                    else if (t.Context.Type == "artist")
                    {
                        tuple1 = client.Download(builder.GetArtist(t.Track.Album.Uri.Substring(15)), headers);
                        var obj3 = JsonConvert.DeserializeObject <FullArtist>(tuple1.Item2);
                        list.Add(new SimplePlaylist()
                        {
                            Name = obj3.Name, Id = obj3.Id, Images = obj3.Images, Type = obj3.Type
                        });
                    }
                }

                return(list.GroupBy(x => x.Name).Select(g => g.First()).ToList());
            }
            catch { return(null); }
        }
        public async Task NextPageForCursorPaging()
        {
            var api     = new Mock <IAPIConnector>();
            var config  = SpotifyClientConfig.CreateDefault("FakeToken").WithAPIConnector(api.Object);
            var spotify = new SpotifyClient(config);

            var response = new CursorPaging <PlayHistoryItem>
            {
                Next = "https://next-url"
            };

            await spotify.NextPage(response);

            api.Verify(a => a.Get <CursorPaging <PlayHistoryItem> >(new System.Uri("https://next-url")), Times.Once);
        }
        /// <inheritdoc/>
        public void GetRecentlyPlayedMusicForActivitiesWithMultipleSources()
        {
            var tokenAsJson      = externalAPIGateway.GetSpotifyAuthenticationToken();
            var spotifyAuthToken = JsonConvert.DeserializeObject <SpotifyAuthenticationToken>((string)tokenAsJson.Value);

            foreach (var item in searchResults)
            {
                if (item is StravaActivity activity)
                {
                    DateTimeOffset startDateAsDateTime = activity.start_date;

                    // Get Spotify songs
                    var spotifySearchResult = externalAPIGateway.GetSpotifyRecentlyPlayed(spotifyAuthToken.AccessToken, startDateAsDateTime);
                    CursorPaging <PlayHistoryItem> playHistoryContainer = (CursorPaging <PlayHistoryItem>)spotifySearchResult.Value;
                    List <PlayHistoryItem>         spotifyFoundSongs    = playHistoryContainer.Items.ToList();
                    // Get Last.FM songs
                    var lastFMSearchResult = externalAPIGateway.GetLastFMRecentlyPlayed(userName, startDateAsDateTime);
                    PageResponse <LastTrack> lastTrackHistoryContainer = (PageResponse <LastTrack>)lastFMSearchResult.Value;
                    List <LastTrack>         lastFMFoundSongs          = lastTrackHistoryContainer.Content.ToList();
                    // Map songs to activity
                    var tempDict = SongsToActivityMapper.MapSongsToActivity(activity, spotifyFoundSongs, lastFMFoundSongs);
                    tempDict.ToList().ForEach(x => activitiesAndSongs.Add(x.Key, x.Value));
                }

                if (item is Fitbit.Api.Portable.Models.Activities fitbitActivity)
                {
                    DateTimeOffset startDateAsDateTime = fitbitActivity.StartTime;
                    // Get Spotify songs
                    var spotifySearchResult = externalAPIGateway.GetSpotifyRecentlyPlayed(spotifyAuthToken.AccessToken, startDateAsDateTime);
                    CursorPaging <PlayHistoryItem> playHistoryContainer = (CursorPaging <PlayHistoryItem>)spotifySearchResult.Value;
                    List <PlayHistoryItem>         spotifyFoundSongs    = playHistoryContainer.Items.ToList();
                    // Get Last.FM songs
                    var lastFMSearchResult = externalAPIGateway.GetLastFMRecentlyPlayed(userName, fitbitActivity.StartTime);
                    PageResponse <LastTrack> lastTrackHistoryContainer = (PageResponse <LastTrack>)lastFMSearchResult.Value;
                    List <LastTrack>         lastFMFoundSongs          = lastTrackHistoryContainer.Content.ToList();
                    // Map songs to activity
                    var tempDict = SongsToActivityMapper.MapSongsToActivity(fitbitActivity, spotifyFoundSongs, lastFMFoundSongs);
                    tempDict.ToList().ForEach(x => activitiesAndSongs.Add(x.Key, x.Value));
                }
            }
        }
        public static void RecordSongs(CursorPaging <PlayHistory> recentData, SpotifyWebAPI api)
        {
            var mostRecentHistory = ConvertToExtendedPlayHistory(recentData).ToList();
            var groupedHistory    = mostRecentHistory.GroupBy(x => x.Track.Id);
            var distinctHistory   = new List <ExtendedPlayHistory>();

            foreach (var group in groupedHistory)
            {
                var song = group.ToList()[0];
                song.TimesPlayed = group.Count();
                distinctHistory.Add(song);
            }

            distinctHistory = distinctHistory.OrderByDescending(x => x.TimesPlayed).ToList();
            var previousDistinctHistory = FileManager.GetLikedSongs();

            AddTogetherSongs(ref distinctHistory, previousDistinctHistory);
            //PlaylistCreator.CreatePlaylist(distinctHistory, api, 2);
            FileManager.SaveSongs(distinctHistory);
            FileManager.SaveTimeStamp();
        }
Пример #11
0
        public async Task <SimpleTrack> GetLastPlayedSongAsync()
        {
            await CheckForConnectionAsync();

            if (!string.IsNullOrEmpty(_spotify?.AccessToken))
            {
                CursorPaging <PlayHistory> playbackHistory = await _spotify.GetUsersRecentlyPlayedTracksAsync(1);

                if (playbackHistory.Error == null)
                {
                    await CheckForConnectionAsync();

                    if (playbackHistory.Items.Count > 0)
                    {
                        return(playbackHistory.Items[0].Track);
                    }
                }
            }

            return(null);
        }
Пример #12
0
        static void Main(string[] args)
        {
            Session session = new Session();


            string userInput = "";

            do
            {
                Console.WriteLine("Enter a command");
                userInput = Console.ReadLine();

                if (userInput == "play")
                {
                    SearchItem item = Session.api.SearchItems("roadhouse+blues", SearchType.Album | SearchType.Playlist);
                    Console.WriteLine(item.Albums.Total); //How many results are there in total? NOTE: item.Tracks = item.Artists


                    CursorPaging <PlayHistory> histories = Session.api.GetUsersRecentlyPlayedTracks();
                }
            } while (userInput != "q");
        }
 public CursorPaging <TDestination> Convert(NavigationResponse <TSource> source,
                                            CursorPaging <TDestination> destination,
                                            ResolutionContext context)
 {
     if (source != null)
     {
         var list        = source.Items.ToList();
         var itemMapping = context.Mapper.Map <IEnumerable <TSource>, IEnumerable <TDestination> >(list);
         var response    = new CursorPaging <TDestination>
         {
             Href   = source.Href,
             Before = source.Back,
             Items  = itemMapping.ToList(),
             Error  = context.Mapper.Map <Responses.ErrorResponse>(source.Error),
             Limit  = source.Limit,
             Next   = source.Next,
             Offset = source.Offset,
             Total  = source.Total
         };
         return(response);
     }
     return(null);
 }
        public JsonResult GetSpotifyRecentlyPlayed(string access_token, DateTimeOffset?after = null, double?duration = null)
        {
            CursorPaging <PlayHistoryItem> playHistory = new CursorPaging <PlayHistoryItem>();
            var tempToken = new SpotifyAuthenticationToken {
                AccessToken = access_token
            };

            if (after != null)
            {
                DateTimeOffset actualAfter = (DateTimeOffset)after;
                var            afterAsUnix = actualAfter.ToUnixTimeMilliseconds();
                playHistory = (CursorPaging <PlayHistoryItem>) this.dataSource.GetSpotifyRecentlyPlayed(tempToken, afterAsUnix).Result.Value;

                if (duration != null)
                {
                    var actualDuration = (double)duration;
                    var end            = actualAfter.AddSeconds(actualDuration);
                    var validSongs     = new List <PlayHistoryItem>();
                    foreach (var track in playHistory.Items)
                    {
                        if (track.PlayedAt >= actualAfter && track.PlayedAt < end)
                        {
                            validSongs.Add(track);
                        }
                    }
                    playHistory.Items = validSongs;
                    return(new JsonResult(playHistory));
                }

                return(new JsonResult(playHistory));
            }
            else
            {
                playHistory = (CursorPaging <PlayHistoryItem>) this.dataSource.GetSpotifyRecentlyPlayed(tempToken, null).Result.Value;
                return(new JsonResult(playHistory));
            }
        }
Пример #15
0
 public FullTrack GetLatestTrack()
 {
     if (m_spotifyWebAPI != null)
     {
         if (m_spotifyWebAPI.GetPlayback().IsPlaying || m_spotifyWebAPI.GetPlayingTrack().Item != null)
         {
             return(m_spotifyWebAPI.GetPlayingTrack().Item);
         }
         else
         {
             FullTrack latestTrack = m_spotifyWebAPI.GetPlayingTrack().Item;
             if (latestTrack != null)
             {
                 return(latestTrack);
             }
             else if (m_spotifyWebAPI.GetUsersRecentlyPlayedTracks().Error == null)
             {
                 CursorPaging <PlayHistory> history = m_spotifyWebAPI.GetUsersRecentlyPlayedTracks();
                 return(m_spotifyWebAPI.GetTrack(history.Items[0].Track.Id));
             }
         }
     }
     return(null);
 }
Пример #16
0
 public List <SimpleTrack> ToList(CursorPaging <PlayHistory> history)
 {
     return(history.Items.Select(playHistory => playHistory.Track).ToList());
 }
Пример #17
0
        public async Task <ActionResult> Index(IndexViewModel viewModel)
        {
            TempData["Playlist"]  = null;
            viewModel.isFromIndex = true;
            viewModel.profile     = (PrivateProfile)TempData["User"];
            viewModel.api         = (SpotifyWebAPI)TempData["Api"];
            Token token = (Token)TempData["Token"];
            AuthorizationCodeAuth auth = (AuthorizationCodeAuth)TempData["Auth"];

            if (token != null)
            {
                if (token.IsExpired())
                {
                    Token newToken = await auth.RefreshToken(token.RefreshToken);

                    viewModel.api.AccessToken = newToken.AccessToken;
                    viewModel.api.TokenType   = newToken.TokenType;
                }

                CursorPaging <PlayHistory> histories = viewModel.api.GetUsersRecentlyPlayedTracks(20);
                Paging <FullArtist>        artists   = viewModel.api.GetUsersTopArtists(TimeRangeType.ShortTerm, 20);

                //creates a random list from 0 to the number of recent tracks and 0 to recent artists
                //then shuffled to be used to display random recent artists and tracks
                //did the same thing for both for the case that there are not 20 recent artists or tracks to get
                //the lists might then be different sizes and could throw an index out of bounds error
                Random     rand            = new Random();
                List <int> randArtistNumbs = new List <int>();
                List <int> randTrackNumbs  = new List <int>();

                for (int i = 0; i < artists.Items.Count; i++)
                {
                    randArtistNumbs.Add(i);
                }
                for (int i = 0; i < histories.Items.Count; i++)
                {
                    randTrackNumbs.Add(i);
                }

                //shuffles the list of artist numbers
                int n = randArtistNumbs.Count;
                while (n > 1)
                {
                    n--;
                    int k    = rand.Next(n + 1);
                    int temp = randTrackNumbs[k];
                    randTrackNumbs[k] = randTrackNumbs[n];
                    randTrackNumbs[n] = temp;
                }

                //shuffle list of track numbers
                int m = randTrackNumbs.Count;
                while (m > 1)
                {
                    m--;
                    int k    = rand.Next(m + 1);
                    int temp = randTrackNumbs[k];
                    randTrackNumbs[k] = randTrackNumbs[m];
                    randTrackNumbs[m] = temp;
                }

                //adds up to 5 recent artists to the top artists view property
                for (int i = 0; i < 5; i++)
                {
                    if (artists.Items[randArtistNumbs[i]] != null)
                    {
                        viewModel.topArtists.Add(artists.Items[randArtistNumbs[i]]);
                    }
                }
                //adds non duplicate tracks to the recent tracks property
                viewModel.recentTracks = new Playlist();
                int count = 0;
                while (viewModel.recentTracks.TrackList.Count < 5 && count < randTrackNumbs.Count)
                {
                    string trackId = histories.Items[randTrackNumbs[count]].Track.Id;
                    if (!viewModel.recentTracks.hasTrack(trackId))
                    {
                        viewModel.recentTracks.TrackList.Add(viewModel.api.GetTrack(trackId));
                    }
                    count++;
                }
            }

            ViewBag.FlashMessage = (string)TempData["FlashMessage"];

            if (TempData["isError"] != null)
            {
                ViewBag.isError = (bool)TempData["isError"];
            }

            TempData["User"]        = viewModel.profile;
            TempData["Api"]         = viewModel.api;
            TempData["Token"]       = token;
            TempData["Auth"]        = auth;
            TempData["isFromIndex"] = true;
            TempData["ViewModel"]   = viewModel;
            return(View(viewModel));
        }
Пример #18
0
    public CursorPaging <PlayHistory> GetRecentlyPlayed()
    {
        CursorPaging <PlayHistory> recentlyPlayed = _spotify.GetUsersRecentlyPlayedTracks();

        return(recentlyPlayed);
    }
Пример #19
0
 public Task <CursorPaging <T> > NextPage <T>(CursorPaging <T> cursorPaging)
 {
     throw new NotImplementedException();
 }
Пример #20
0
 public static NavigationResponse <ArtistResponse> MapFromCursorPaging(this IMapper mapper, CursorPaging <Artist> artists) =>
 mapper.Map <NavigationResponse <ArtistResponse> >(artists);
Пример #21
0
 public List <FullArtist> ToList(CursorPaging <FullArtist> artists)
 {
     return(artists.Items.Select(artist => artist).ToList());
 }
Пример #22
0
 public CursorPaging <T> GetNextPage <T, TSettings>(SpotifyImportListBase <TSettings> list, SpotifyWebAPI api, CursorPaging <T> item)
     where TSettings : SpotifySettingsBase <TSettings>, new()
 {
     return(Execute(list, api, (x) => x.GetNextPage(item)));
 }
Пример #23
0
 public static NavigationResponse <AlbumResponse> MapFromCursorPaging(this IMapper mapper, CursorPaging <SavedAlbum> albums) =>
 mapper.Map <NavigationResponse <AlbumResponse> >(albums);
Пример #24
0
 public static NavigationResponse <TrackResponse> MapFromCursorPaging(this IMapper mapper, CursorPaging <PlayHistory> tracks) =>
 mapper.Map <NavigationResponse <TrackResponse> >(tracks);
Пример #25
0
 public static NavigationResponse <PlaylistResponse> MapFromCursorPaging(this IMapper mapper, CursorPaging <SimplifiedPlaylist> playlists) =>
 mapper.Map <NavigationResponse <PlaylistResponse> >(playlists);
Пример #26
0
 public static NavigationResponse <ShowResponse> MapFromCursorPaging(this IMapper mapper, CursorPaging <SavedShow> shows) =>
 mapper.Map <NavigationResponse <ShowResponse> >(shows);