예제 #1
0
        protected override async Task ProcessInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false)
        {
            ListenGroup = await ListenSessionService.GetGroupAsync(ChatServices.Telegram, message.Chat.Id.ToString());

            if (ListenGroup != null)
            {
                OwnerSpotifyClient = await SpotifyService.GetClientAsync(ListenGroup.OwnerMBUserId);

                MessageSenderSpotifyClient = await SpotifyService.GetClientAsync(user);

                try
                {
                    CurrentGroupPlaylist = await OwnerSpotifyClient.Playlists.Get(ListenGroup.SpotifyPlaylistId);

                    if (CurrentGroupPlaylist == null)
                    {
                        // TODO: handle User deleted playlist
                        logger.LogError("Playlist wasn't found.. must have been deleted");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Error retrieving playlist");
                }
            }
            else if (RequiresActiveGroup)
            {
                logger.LogInformation("Requires active group to run this command.");
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "Requires an active group to do this. Run /init");

                return;
            }

            await ProcessListenSessionCommandInternalAsync(user, message, logger, isAuthorizationCallback);
        }
예제 #2
0
        private static async Task <string> CreatePlaylist(SpotifyWebAPI api, string playlistName)
        {
            PrivateProfile profile = await api.GetPrivateProfileAsync();

            string name = string.IsNullOrEmpty(profile.DisplayName) ? profile.Id : profile.DisplayName;

            profileId = profile.Id;
            Console.WriteLine($"Hello there, {name}!");

            Console.WriteLine("Will create a new playlist with name: " + playlistName);

            FullPlaylist playlist = api.CreatePlaylist(profileId, playlistName, false);

            if (!playlist.HasError())
            {
                //Store the ID for future use
                playlistId = playlist.Id;
            }
            Console.WriteLine("Playlist-URI: " + playlist.Uri);
            Console.WriteLine("Playlist-ID: " + playlist.Id);

            return(playlist.Id);
        }
예제 #3
0
        public async void LoadCommit(string pathName)
        {
            //Commit holen
            derCommit = dieDaten.GetCommitAt(pathName);

            //Commit anzeigen
            string[] tracks = derCommit.GetOld();
            tracks = await getSeveralTracksNamesAsync(tracks);

            dieGUI.Listbox_SetContent(tracks, null);

            string[] addedTracksItems = derCommit.GetAdded();
            string[] addedTracksNames = await getSeveralTracksNamesAsync(addedTracksItems);

            for (int i = 0; i < addedTracksItems.Length; i++)
            {
                string track_name = addedTracksNames[i];
                int    index      = dieGUI.Listbox_AddItem(track_name);
                dieGUI.Listbox_PaintAddedSongs(index);
            }

            int[] uri_rem = derCommit.GetRemoved();
            dieGUI.Listbox_PaintRemovedSongs(uri_rem);

            dieGUI.UpdateDiffindicator();

            //GUI-Modus ändern und Playlist-Infos anzeigen
            dieGUI.ChangeMode(GUIMode.Load);
            string id = derCommit.GetPlaylistId();

            if (id != l303.Id) //Wenn Id nicht gleich bereits geladener Id ist
            {
                FullPlaylist playl = await api.GetPlaylistAsync("lambade303", id);

                dieGUI.SetPlaylistInfo(playl.Name, playl.Owner.DisplayName, playl.Tracks.Total, DateTime.Now);
            }
        }
예제 #4
0
        public async Task <Dictionary <string, string> > GetTop50UsaPlaylistDictAsync(SpotifyWebAPI spotify)
        {
            Dictionary <string, string> dict = new Dictionary <string, string>();

            FullPlaylist top50UsaPlaylist = await spotify.GetPlaylistAsync("37i9dQZEVXbLRQDuF5jeBp");

            if (top50UsaPlaylist.HasError())
            {
                Console.WriteLine("Error Status: " + top50UsaPlaylist.Error.Status);
                Console.WriteLine("Error Msg: " + top50UsaPlaylist.Error.Message);

                return(null);
            }

            foreach (PlaylistTrack track in top50UsaPlaylist.Tracks.Items)
            {
                if (!dict.ContainsKey(track.Track.Id))
                {
                    dict.Add(track.Track.Id, track.Track.Name);
                }
            }

            return(dict);
        }
예제 #5
0
 private void AddFiles(object sender, RoutedEventArgs e)
 {
     FullPlaylist.AddUniqueElements();
     this.mediaPlaylist.ItemsSource = FullPlaylist.MediaCollection;
 }
예제 #6
0
 public static SpotifyPlaylist Convert(FullPlaylist spotifyPlaylist) => new()
예제 #7
0
        private static async Task testPlayArtistTrack(SpotifyWebAPI api)
        {
            PrivateProfile profile = await api.GetPrivateProfileAsync();



            //    AvailabeDevices devices = api.GetDevices();
            //    devices.Devices.ForEach(device => Console.WriteLine(device.Name));


            var devices = api.GetDevices();

            if (devices.Devices != null)
            {
                var device_id = devices.Devices[0].Id;
                Console.WriteLine("Device id=" + device_id);
            }
            else
            {
                Console.WriteLine("no devices!");
            }


            Paging <SimpleTrack> tracks = api.GetAlbumTracks("2gcHtTSYMn8VhYlUdkI6kd");

            foreach (var track in tracks.Items)
            {
                Console.WriteLine("name=" + track.Name + " id=" + track.Id);
                //play it
                ;

                FullPlaylist list = api.CreatePlaylist(profile.Id, "test track");
                //   4iV5W9uYEdYUVa79Axb7Rh
                //    6MCSPhkasUOCC43gwP0Mqb

                //   ErrorResponse resp= api.AddPlaylistTrack(list.Id, "spotify:track:4iV5W9uYEdYUVa79Axb7Rh");

                //      Console.WriteLine("AddPlaylistTrack:" +resp.Error.Message.ToString()+resp.Error.Status);
                //     resp=api.PausePlayback();

                //       Console.WriteLine("PausePlayback:" + resp.Error.Message.ToString() + resp.Error.Status);

                ErrorResponse resp = api.ResumePlayback("", "", new List <string> {
                    "spotify:track:6MCSPhkasUOCC43gwP0Mqb"
                }, "", 0);

                if (resp.HasError())
                {
                    Console.WriteLine("ResumePlayback:" + resp.Error.Message.ToString() + "\n" + resp.Error.Status);
                }

                //    ErrorResponse error = api.ResumePlayback(uris: new List<string> { "spotify:track:4iV5W9uYEdYUVa79Axb7Rh" });

                var playback = api.GetPlayback();
                if (playback == null)
                {
                    Console.WriteLine("no playback!");
                    return;
                }

                Console.WriteLine("is playing?" + playback.IsPlaying);
                if (playback.IsPlaying)
                {
                    Console.WriteLine(" ... playing:" + playback.Item.Name);
                }
            }
        }
예제 #8
0
            public static EmbedFieldBuilder PreviousPlaybackField(SocketVoiceChannel oldChannel, FullPlaylist previousPlaylist)
            {
                var embedField = new EmbedFieldBuilder()
                                 .WithName($"Previous Playback Channel: {oldChannel.Name}")
                                 .WithValue($"Active Playlist: [{previousPlaylist.Name}]({previousPlaylist.ExternalUrls.First().Value}) From: [{previousPlaylist.Owner.Id}]({previousPlaylist.Owner.ExternalUrls.First().Value})")
                                 .WithIsInline(false);

                return(embedField);
            }
예제 #9
0
        public async Task ShouldMakeAuthenticatedCallAndRenewAccessTokenWhenItIsNotValidOrUnauthorizedExceptionIsThrownAsync()
        {
            // Arrange
            this.SystemClockMock.SetupSequence(x => x.UtcNow)
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 1)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)));

            const string refreshToken = "test refresh token";
            const string accessToken1 = "test access token 1";
            const string accessToken2 = "test access token 2";
            const string accessToken3 = "test access token 3";

            var accessTokenDto2 = new AccessTokenDto {
                ExpiresIn = 3600, Token = accessToken2
            };
            var accessTokenDto3 = new AccessTokenDto {
                ExpiresIn = 3600, Token = accessToken3
            };

            const string playlistId        = "test playlist";
            var          expectedPlaylist1 = new FullPlaylist {
                Id = playlistId, Description = "playlist 1"
            };
            var expectedPlaylist2 = new FullPlaylist {
                Id = playlistId, Description = "playlist 2"
            };
            var expectedPlaylist3 = new FullPlaylist {
                Id = playlistId, Description = "playlist 3"
            };

            const string userId = "test user";

            this.AuthenticationManager.SetAuthenticateResult((userId, refreshToken, accessToken1, new DateTimeOffset(new DateTime(2005, 1, 1, 3, 0, 0))));

            this.MockGetAccessToken(refreshToken)
            .Returns(Task.FromResult(accessTokenDto2))
            .Returns(Task.FromResult(accessTokenDto3));

            this.MockGetPlaylistHttpClientWrapper(userId, playlistId, accessToken1)
            .Returns(Task.FromResult(expectedPlaylist1));

            this.MockGetPlaylistHttpClientWrapper(userId, playlistId, accessToken2)
            .Returns(Task.FromResult(expectedPlaylist2))
            .Throws(new SpotifyHttpResponseWithErrorCodeException(System.Net.HttpStatusCode.Unauthorized, null, string.Empty));

            this.MockGetPlaylistHttpClientWrapper(userId, playlistId, accessToken3)
            .Returns(Task.FromResult(expectedPlaylist3));

            // Act + Assert
            var playlist1 = await this.Client.Me.Playlist(playlistId).GetAsync();

            playlist1.ShouldBeEquivalentTo(expectedPlaylist1);

            var playlist2 = await this.Client.Me.Playlist(playlistId).GetAsync();

            playlist2.ShouldBeEquivalentTo(expectedPlaylist2);

            var playlist3 = await this.Client.Me.Playlist(playlistId).GetAsync();

            playlist3.ShouldBeEquivalentTo(expectedPlaylist3);
        }
예제 #10
0
        private async void btnUpload_Click(object sender, EventArgs e)
        {
            _failedTofindSongs           = new List <MusicItem>();
            _completelyFailedTofindSongs = new List <MusicItem>();

            var auth = new ImplicitGrantAuth(
                _clientId,
                "http://localhost:4002",
                "http://localhost:4002",
                Scope.UserLibraryModify | Scope.PlaylistModifyPrivate
                );

            auth.Start();
            auth.OpenBrowser();

            auth.AuthReceived += async(s, payload) =>
            {
                auth.Stop();
                _spotifyAPI = new SpotifyWebAPI()
                {
                    TokenType   = payload.TokenType,
                    AccessToken = payload.AccessToken
                };

                String       line;
                String       artist = "testing";
                Boolean      found  = false;
                StreamReader file   = new StreamReader(_playlistLocation);

                List <MusicItem> musicItems = new List <MusicItem>();

                while ((line = file.ReadLine()) != null && !String.IsNullOrWhiteSpace(line))
                {
                    //line example: D:\Users\Paul\Music\Paul Music\Plus44\When Your Heart Stops Beating\12-plus_44-chapter_xiii.mp3
                    string[] artistPlusSong = null;
                    string[] slashPlusRest  = null;

                    try
                    {
                        artistPlusSong = line.Split(new string[] { "Paul Music\\" }, StringSplitOptions.None);
                        slashPlusRest  = artistPlusSong[1].Split('\\');
                        var musicItem = new MusicItem(line, slashPlusRest[0], Path.GetFileNameWithoutExtension(slashPlusRest[1]));
                        musicItems.Add(musicItem);
                        artist = slashPlusRest[0].ToLower();
                    }
                    catch (System.IndexOutOfRangeException ex)
                    {
                        System.Console.WriteLine(line);
                    }
                }

                FullPlaylist playlist = null;

                if (!debug)
                {
                    playlist = await _spotifyAPI.CreatePlaylistAsync(_spotifyAPI.GetPrivateProfile().Id, artist, false);
                }

                foreach (var music in musicItems) // find the song on Spotify and add to playlist
                {
                    String query = String.Format("artist:{0} track:{1}", music.artist, music.title);
                    await doSearch(query, music, _failedTofindSongs, playlist?.Id ?? "");
                }

                // need to try searching with tags instead of filename
                foreach (var failedMusic in _failedTofindSongs)
                {
                    var tFile = TagLib.File.Create(failedMusic.line);

                    if (!String.IsNullOrWhiteSpace(tFile.Tag.FirstAlbumArtist))
                    {
                        failedMusic.artist = tFile.Tag.FirstAlbumArtist;
                    }
                    else if (!String.IsNullOrWhiteSpace(tFile.Tag.FirstPerformer))
                    {
                        failedMusic.artist = tFile.Tag.FirstPerformer;
                    }
                    else if (!String.IsNullOrWhiteSpace(tFile.Tag.FirstArtist))
                    {
                        failedMusic.artist = tFile.Tag.FirstArtist;
                    }
                    else
                    {
                        Console.WriteLine(failedMusic.artist + " not in tags");
                    }

                    if (!String.IsNullOrWhiteSpace(tFile.Tag.Title))
                    {
                        failedMusic.title = tFile.Tag.Title;
                    }
                    else
                    {
                        Console.WriteLine(failedMusic.title + " not in tags");
                    }

                    String q = String.Format("artist:{0} track:{1}", failedMusic.artist, failedMusic.title);
                    await doSearch(q, failedMusic, _completelyFailedTofindSongs, playlist?.Id ?? "");
                }

                Console.WriteLine("LIST OF COMPLETELY FAILED: ");
                foreach (var failed in _completelyFailedTofindSongs)
                {
                    Console.WriteLine(failed.line);
                }

                //todo do tag online lookup
            };
        }
예제 #11
0
    public bool isPlaylist(string id)
    {
        FullPlaylist playlist = _spotify.GetPlaylist(id, "", "");;

        return(!playlist.HasError());
    }
예제 #12
0
        public static FullPlaylist CreatePlaylist(string playlistName, string userID, SpotifyWebAPI authObj)
        {
            FullPlaylist spotifyPlaylist = authObj.CreatePlaylist(userID, playlistName);

            return(spotifyPlaylist);
        }
예제 #13
0
        private void CreatePlaylist(List <string> tracks)
        {
            FullPlaylist  newReleases = spotify.CreatePlaylist(profile.Id, DateTime.Now.ToString("MM/dd") + " Releases");
            SearchItem    song        = new SearchItem();
            ErrorResponse response    = new ErrorResponse();

            if (newReleases.HasError()) //This might need more graceful integration
            {
                Console.WriteLine(newReleases.Error.Message);
            }

            // Passes cursor update to main thread
            mainThread.Post((object state) => { Mouse.OverrideCursor = Cursors.Wait; Status.Text = "Status: Searching"; }, null);


            foreach (string target in tracks)
            {
                if (target.Contains("EP") || target.Contains("Album") || target.Contains("Remixes"))
                {
                    song = spotify.SearchItems(target, SearchType.Album);
                    if (song.Albums.Total > 0)
                    {
                        FullAlbum album = spotify.GetAlbum(song.Albums.Items[0].Id);
                        for (int i = 0; i < album.Tracks.Total; i++)
                        {
                            response = spotify.AddPlaylistTrack(profile.Id, newReleases.Id, album.Tracks.Items[i].Uri);

                            // Passes listbox ui update to main thread
                            mainThread.Send((object state) => {
                                songs.Add(new Song()
                                {
                                    SongTitle = album.Tracks.Items[i].Name
                                });
                            }, null);
                        }
                    }
                }
                else
                {
                    song = spotify.SearchItems(target, SearchType.Track);
                    if (song.Tracks.Items.Count > 0)
                    {
                        response = spotify.AddPlaylistTrack(profile.Id, newReleases.Id, song.Tracks.Items[0].Uri);

                        // Passes listbox ui update to main thread
                        mainThread.Send((object state) => {
                            songs.Add(new Song()
                            {
                                SongTitle = song.Tracks.Items[0].Name
                            });
                        }, null);
                    }

                    if (response.HasError()) //This might need more graceful integration
                    {
                        Console.WriteLine(response.Error.Message);
                    }
                }

                // pass percent complete updates to main thread
                mainThread.Send((object state) => {
                    percentDone      += counter;
                    progressBar.Value = percentDone;
                    Amount.Text       = percentDone.ToString("0.") + "%";
                }, null);
            }

            // Passes cursor update to main thread
            mainThread.Post((object state) => { Mouse.OverrideCursor = Cursors.Arrow; Status.Text = "Status: Complete"; }, null);

            MessageBox.Show("Playlist Created!");
            if (response.HasError()) //This might need more graceful integration
            {
                Console.WriteLine(response.Error.Message);
            }
        }
예제 #14
0
        public void UpdateSpot()
        {
            if (initExcpt != null)
            {
                return;
            }

            if (api == null)
            {
                return;
            }

            try
            {
                initExcpt = null;

                var retrievedPlayback = api.GetPlayback();
                if (retrievedPlayback != null)
                {
                    cachedPlayback = retrievedPlayback;
                    if (cachedPlayback.HasError() && cachedPlayback.Error.Message == "The access token expired" && authorized)
                    {
                        authorized = false;
                        Authorize();
                    }
                }

                if (cachedPlayback != null && cachedPlayback.Item != null)
                {
                    var ListedItem = new List <string>(1);
                    ListedItem.Add(cachedPlayback.Item.Id);
                    var response = api.CheckSavedTracks(ListedItem);
                    if (response.List == null)
                    {
                        if (response.HasError() && response.Error.Message == "The access token expired" && authorized)
                        {
                            authorized = false;
                            Authorize();
                        }
                    }
                    else
                    {
                        cachedLikedTrack = response.List[0];
                    }

                    if (cachedPlayback.Context == null)
                    {
                    }
                    else if (cachedPlayback.Context.Type == "playlist")
                    {
                        var split       = cachedPlayback.Context.ExternalUrls["spotify"].Split('/');
                        var newPlaylist = api.GetPlaylist(split[4]);
                        if (newPlaylist != null && !newPlaylist.HasError())
                        {
                            cachedPlaylist = newPlaylist;
                        }
                    }
                    else if (cachedPlayback.Context.Type == "album")
                    {
                        var newAlbum = api.GetAlbum(cachedPlayback.Item.Album.Id);
                        if (newAlbum != null && !newAlbum.HasError())
                        {
                            cachedAlbum = newAlbum;
                        }

                        if (upNextAlbumTrack != null)
                        {
                            if (cachedPlayback.Item.TrackNumber + 1 > newAlbum.Tracks.Items.Count)
                            {   // just go back to 0 i guess?
                                upNextAlbumTrackFull = api.GetTrack(newAlbum.Tracks.Items[0].Id);
                            }
                            else
                            {
                                upNextAlbumTrackFull = api.GetTrack(newAlbum.Tracks.Items[cachedPlayback.Item.TrackNumber + 1].Id);
                            }
                        }
                        else
                        {
                            upNextAlbumTrackFull = null;
                        }
                    }
                    else if (cachedPlayback.Context.Type == "artist")
                    {
                        var split  = cachedPlayback.Context.ExternalUrls["spotify"].Split('/');
                        var region = RegionInfo.CurrentRegion;

                        upNextAlbumTrackFull = null;

                        var artistTracks = api.GetArtistsTopTracks(split[4], region.TwoLetterISORegionName);
                        var thisArtist   = api.GetArtist(split[4]);

                        if (thisArtist != null)
                        {
                            cachedArtist = thisArtist;
                        }

                        for (int i = 0; i < artistTracks.Tracks.Count; i++)
                        {
                            if (artistTracks.Tracks[i].Id == cachedPlayback.Item.Id)
                            {
                                if (i == artistTracks.Tracks.Count - 1)
                                {
                                    upNextAlbumTrackFull = artistTracks.Tracks[0];
                                    break;
                                }
                                else
                                {
                                    upNextAlbumTrackFull = artistTracks.Tracks[i + 1];
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (AggregateException /*e*/)
            {
                //initExcpt = e; // This is common if the task was dropped
            }
        }
예제 #15
0
 public ListingPlaylist(FullPlaylist fp)
 {
     Playlist   = fp;
     Id         = fp.Id;
     TrackCount = fp?.Tracks?.Total;
 }
예제 #16
0
 private void PlaySelectedMedia(object sender, MouseButtonEventArgs e)
 {
     FullPlaylist.PlaySelectedItem((Media)mediaPlaylist.SelectedItem);
 }
 public PlaylistInfo(float acousticness, float danceability, float energy, float instrumentalness, float loudness, float valence, float tempo, PlaylistPopularityBalance playlistPopularityBalance, FullPlaylist playlist)
 {
     Acousticness              = acousticness;
     Danceability              = danceability;
     Energy                    = energy;
     Instrumentalness          = instrumentalness;
     Loudness                  = loudness;
     Valence                   = valence;
     Tempo                     = tempo;
     PlaylistPopularityBalance = playlistPopularityBalance;
     Playlist                  = playlist;
 }
예제 #18
0
        public override async Task OperateCommand(CommandContext ctx, params string[] args)
        {
            await base.OperateCommand(ctx, args);

            string    subCommand = args[0];
            guildData data       = Utils.returnGuildData(ctx.Guild.Id);

            switch (subCommand.ToLower())
            {
            case "play":
                //Play the tunes!
                await VoiceJoin(ctx);

                //We need to download the spotify song or whatever
                if (args[1] != null)
                {
                    //Start to play the song
                    if (args[1].Contains("youtube") || args[1].Contains("youtu.be"))
                    {
                    }
                    else if (args[1].Contains("spotify"))
                    {
                        //Initialise the spotify bot if has not done yet!
                        if (api == null)
                        {
                            CredentialsAuth auth  = new CredentialsAuth("7c09a36e2ef84c2abc068c8979103d17", "d21bc05a3f604089b176e3b3e5975e0b");
                            Token           token = await auth.GetToken();

                            api = new SpotifyWebAPI
                            {
                                AccessToken = token.AccessToken,
                                TokenType   = token.TokenType
                            };
                        }

                        string uriCode = null;
                        Uri    uri     = new UriBuilder(args[1]).Uri;

                        if (args[1] != null)
                        {
                            //Get the spotify track from url or the uri code
                            uriCode = uri.Segments[2];
                        }

                        if (uriCode != null)
                        {
                            if (uri.Segments[1] == "track")
                            {
                                FullTrack track = await api.GetTrackAsync(uriCode);

                                if (track.Artists != null)
                                {
                                    List <string> artists = new List <string>();
                                    foreach (SimpleArtist artist in track.Artists)
                                    {
                                        artists.Add(artist.Name);
                                    }
                                    string connectArtist = string.Join(",", artists.ToArray());
                                    await ctx.RespondAsync("Playing: " + track.Name + " By: " + connectArtist);
                                }
                                if (track.HasError())
                                {
                                    await ctx.RespondAsync("The track when playing had an issue!");
                                }
                            }
                            else if (uri.Segments[1] == "playlist")
                            {
                                //Playlist
                                FullPlaylist list = await api.GetPlaylistAsync(uriCode);

                                await ctx.RespondAsync("Playing: " + list.Name);

                                if (list.HasError())
                                {
                                    await ctx.RespondAsync("The playlist had and issue");
                                }
                            }
                        }
                        else
                        {
                            await ctx.RespondAsync("Invalid url or uri code");
                        }
                    }
                }
                else
                {
                    await ctx.RespondAsync("No song link was defined!");
                }
                break;

            case "stop":
                //Stop the tunes!

                break;

            case "leave":
            case "fuckoff":
                //Leave the channel forcefully!
                await VoiceLeave(ctx);

                break;

            case "autoleave":
                //Set if the bot should automatically leave the voice channel when no one is in the voice channel
                if (data.autoSongLeave == false)
                {
                    data.autoSongLeave = true;
                    await ctx.RespondAsync("This bot will leave the party when everyone else has finished!");
                }
                else if (data.autoSongLeave == true)
                {
                    data.autoSongLeave = false;
                    await ctx.RespondAsync("This bot will keep on partying!");
                }
                break;

            case "loop":
                //loop the song that is currently playing
                if (data.loopSong == false)
                {
                    data.loopSong = true;
                    await ctx.RespondAsync("Looping Song !");
                }
                else if (data.loopSong == true)
                {
                    data.loopSong = false;
                    await ctx.RespondAsync("Not Looping Song!");
                }
                break;

            default:
            case "help":
                //Show the help on it.
                Dictionary <string, string> argumentsHelp = new System.Collections.Generic.Dictionary <string, string>();
                argumentsHelp.Add(";;song play", "specify a song right after play with a space then this bot will play or specify a link (overrides queue)");
                argumentsHelp.Add(";;song stop", "stop whatever is playing");
                argumentsHelp.Add(";;song leave", "forces the bot to leave the current voice channel");
                argumentsHelp.Add(";;song autoleave", "turns on auto leave the bot will leave the channel when no one is present");
                argumentsHelp.Add(";;song loop", "loops the current song and disables queue");
                DiscordEmbed embedHelp = JosephineEmbedBuilder.CreateEmbedMessage(ctx, "Sub-Commands", "for ';;announce set'", null, JosephineBot.defaultColor, argumentsHelp, false);
                await ctx.RespondAsync("Go to http://discord.rickasheye.xyz/ for all sub-commands", false, embedHelp);

                break;
            }
        }
예제 #19
0
 private void AddTrack(FullPlaylist playlist, string uri)
 {
     _spotify.AddPlaylistTrack(_dataStorage._profile.Id, playlist.Id, uri);
 }
예제 #20
0
        public ActionResult Index(string q, string t)
        {
            _search  = q;
            _trackId = t;

            SetReturnUrl(_search, _trackId);

            if (string.IsNullOrEmpty(_search))
            {
                return(RedirectToAction("Index", "Home"));
            }

            Token token = _tokenService.GetToken();

            if (string.IsNullOrEmpty(token.AccessToken) && !string.IsNullOrEmpty(token.RefreshToken))
            {
                string oldRefreshToken = token.RefreshToken;
                token = RefreshToken(token.RefreshToken, Constants.ClientSecret);
                token.RefreshToken = oldRefreshToken;
                _tokenService.SetToken(token);
            }
            else if (string.IsNullOrEmpty(token.AccessToken) && string.IsNullOrEmpty(token.RefreshToken))
            {
                Session["returnUrl"] = "~/Search?q=" + q + "&t=" + t;
                return(RedirectToAction("Index", "Authorize"));
            }

            SearchItem searchItem = Search(_search, token);

            PrivateProfile profile = GetMe(token);

            if (profile.Id == null && token.RefreshToken != null)
            {
                string oldRefreshToken = token.RefreshToken;
                token = RefreshToken(token.RefreshToken, Constants.ClientSecret);
                token.RefreshToken = oldRefreshToken;
                _tokenService.SetToken(token);
                profile = GetMe(token);
            }
            SearchResult result = new SearchResult()
            {
                SearchItem = searchItem,
                query      = _search,
                track      = _trackId,
                Profile    = profile,
            };

            if (profile.Id != null)
            {
                result.Playlists = GetPlaylists(token, profile.Id);
                if (result.Playlists.Items.Count == 0)
                {
                    FullPlaylist fullPlaylist = _paradifyService.CreatePlaylist(profile.Id, "Paradify Playlist", token);

                    if (!string.IsNullOrEmpty(fullPlaylist.Id))
                    {
                        result.Playlists = GetPlaylists(token, profile.Id);
                    }
                }
            }


            _userService.AddUser(profile);

            _historyService.AddSearchHistory(_search, _trackId, profile.Id, AppSource.WebSite);

            return(View(result));
        }
예제 #21
0
            public static Embed ChangePlaylistTrue(SocketCommandContext context, string channelName, FullPlaylist newPlaylist, FullPlaylist previousPlaylist = null)
            {
                var embedNewField = new EmbedFieldBuilder()
                                    .WithName("New Playlist: ")
                                    .WithValue($"[{newPlaylist.Name}]({newPlaylist.ExternalUrls.First().Value})")
                                    .WithIsInline(true);
                var embed = new EmbedBuilder()
                            .WithColor(Color.Green)
                            .WithAuthorFromContext(context)
                            .WithTitle($"{context.User.Username} has changed the playlist in {channelName}")
                            .AddField(embedNewField)
                            .WithCurrentTimestamp();

                if (previousPlaylist == null)
                {
                    return(embed.Build());
                }

                var embedPreviousField = new EmbedFieldBuilder()
                                         .WithName("Previous Playlist: ")
                                         .WithValue($"[{previousPlaylist.Name}]({previousPlaylist.ExternalUrls.First().Value})")
                                         .WithIsInline(true);

                embed.AddField(embedPreviousField);
                return(embed.Build());
            }
예제 #22
0
        public async Task ShouldMakeAuthenticatedCallAndRenewAccessTokenWhenItIsNotValidOrUnauthorizedExceptionIsThrownAsync()
        {
            // Arrange
            this.DateTimeOffsetProviderMock.SetupSequence(x => x.GetUtcNow())
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 1)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 1)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)))
            .Returns(new DateTimeOffset(new DateTime(2005, 1, 2)));

            const string authorizationKey = "test authorization ket";
            const string accessToken1     = "test access token 1";
            const string accessToken2     = "test access token 2";
            const string accessToken3     = "test access token 3";

            var proxyAccessToken2 = new ProxyAccessToken {
                ExpiresIn = 3600, Token = accessToken2
            };
            var proxyAccessToken3 = new ProxyAccessToken {
                ExpiresIn = 3600, Token = accessToken3
            };

            const string playlistId        = "test playlist";
            var          expectedPlaylist1 = new FullPlaylist {
                Id = playlistId, Description = "playlist 1"
            };
            var expectedPlaylist2 = new FullPlaylist {
                Id = playlistId, Description = "playlist 2"
            };
            var expectedPlaylist3 = new FullPlaylist {
                Id = playlistId, Description = "playlist 3"
            };

            var user = this.SetupAuthorizationFlow(authorizationKey: authorizationKey, accessToken: accessToken1);

            this.MockGetAccessToken(authorizationKey)
            .Returns(Task.FromResult(proxyAccessToken2))
            .Returns(Task.FromResult(proxyAccessToken3));

            this.MockGetPlaylistHttpClientWrapper(user.Id, playlistId, accessToken1)
            .Returns(Task.FromResult(expectedPlaylist1));

            this.MockGetPlaylistHttpClientWrapper(user.Id, playlistId, accessToken2)
            .Returns(Task.FromResult(expectedPlaylist2))
            .Throws(new SpotifyHttpResponseWithErrorCodeException(System.Net.HttpStatusCode.Unauthorized, null, string.Empty));

            this.MockGetPlaylistHttpClientWrapper(user.Id, playlistId, accessToken3)
            .Returns(Task.FromResult(expectedPlaylist3));

            // Act + Assert
            await this.AuthenticationManager.RestoreSessionOrAuthorizeUserAsync();

            var playlist1 = await this.Client.Me.Playlist(playlistId).GetAsync();

            playlist1.ShouldBeEquivalentTo(expectedPlaylist1);

            var playlist2 = await this.Client.Me.Playlist(playlistId).GetAsync();

            playlist2.ShouldBeEquivalentTo(expectedPlaylist2);

            var playlist3 = await this.Client.Me.Playlist(playlistId).GetAsync();

            playlist3.ShouldBeEquivalentTo(expectedPlaylist3);
        }
예제 #23
0
            public static Embed Notify(SocketSelfUser bot, SocketVoiceChannel newChannel, FullPlaylist newPlaylist, EmbedFieldBuilder previousPlaybackField = null)
            {
                var embedNewPlayback = new EmbedFieldBuilder()
                                       .WithName($"Joined Channel: {newChannel.Name}\t")
                                       .WithValue($"Active Playlist: [{newPlaylist.Name}]({newPlaylist.ExternalUrls.First().Value}) From: [{newPlaylist.Owner.Id}]({newPlaylist.Owner.ExternalUrls.First().Value})\t")
                                       .WithIsInline(false);
                var embed = new EmbedBuilder()
                            .WithColor(Color.Green)
                            .WithAuthor(bot)
                            .WithTitle($"There's an active playback session in {newChannel.Name}, run \"@{bot.Username} join\" to start listening")
                            .WithCurrentTimestamp();

                if (previousPlaybackField != null)
                {
                    embed.AddField(previousPlaybackField);
                }
                embed.AddField(embedNewPlayback);
                return(embed.Build());
            }
예제 #24
0
        public override void Display()
        {
            Console.WriteLine($"Main Page > Import{Environment.NewLine}---");

            Output.WriteLine(ConsoleColor.Yellow, $"Current account in use {Auth.Profile.DisplayName}");
            Console.Write("Would you like to use the same account? (Y/n) [Default: Y]");
            string Confirm = Console.ReadLine();

            if (Confirm.Trim() == "n")
            {
                Output.WriteLine(ConsoleColor.Red, $"Before continue clean your cookie and browser session, otherwise the same account will be used..{Environment.NewLine}Hit [Enter] to continue...");
                Console.ReadLine();

                Console.WriteLine("Authentication...");
                Auth.Authentication();
                while (!Auth.IsAuthenticated)
                {
                }
                Output.WriteLine(ConsoleColor.Yellow, $"Current account in use {Auth.Profile.DisplayName}");
            }

            Console.Write("Enter path of playlist csv file: ");
            string PathPlaylist = Console.ReadLine();

            if (PathPlaylist.StartsWith('"') && PathPlaylist.EndsWith('"'))
            {
                PathPlaylist = PathPlaylist.Trim('"');
            }

            if (File.Exists(PathPlaylist))
            {
                string PlaylistName = Path.GetFileNameWithoutExtension(PathPlaylist);

                List <CsvPlaylist> Tracks = CsvLoad(PathPlaylist);
                Tracks.OrderBy(t => t.Index);

                Console.WriteLine("Creation of a new playlist...");
                Console.Write($"Would you like to use the same name ({PlaylistName})? (Y/n)");
                Confirm = Console.ReadLine();

                string NewName = string.Empty;

                if (Confirm.Trim() == "n")
                {
                    Console.Write($"Please enter the new name: ");
                    NewName = Console.ReadLine();
                }

                Console.Write($"Would you like to keep the add order of the oldest playlist? [Y (slower) / n (faster)]");
                Confirm = Console.ReadLine();
                bool Order = true;

                if (Confirm.Trim() == "n")
                {
                    Order = false;
                }

                FullPlaylist NewPlaylist = Auth.Spotify.CreatePlaylist(Auth.Profile.Id, NewName == string.Empty ? PlaylistName : NewName, false);
                Console.WriteLine("Import started");
                Console.WriteLine();

                string Format = "0000";

                if (Tracks.Count < 1000)
                {
                    Format = "000";
                }
                else if (Tracks.Count < 100)
                {
                    Format = "00";
                }

                foreach (var Track in Tracks)
                {
                    Console.Write($"\rProcessing: {Track.Index.ToString(Format)}/{Tracks.Count.ToString(Format)}");
                    Auth.Spotify.AddPlaylistTrack(Auth.Profile.Id, NewPlaylist.Id, $"spotify:track:{Track.Id}", Track.Index - 1);

                    if (Order)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }

            Console.WriteLine();
            Output.WriteLine(ConsoleColor.Green, "Import Finished");
            Input.ReadString("Press [Enter] to navigate home");
            Program.NavigateHome();
        }
예제 #25
0
        public async Task <List <IPlaylistSyncError> > SyncToSpotify(MusicBeeSyncHelper mb, List <MusicBeePlaylist> mbPlaylistsToSync,
                                                                     bool includeFoldersInPlaylistName = false, bool includeZAtStartOfDatePlaylistName = true)
        {
            List <IPlaylistSyncError> errors = new List <IPlaylistSyncError>();

            foreach (MusicBeePlaylist playlist in mbPlaylistsToSync)
            {
                // Use LINQ to check for a playlist with the same name
                // If there is one, clear it's contents, otherwise create one
                // Unless it's been deleted, in which case pretend it doesn't exist.
                // I'm not sure how to undelete a playlist, or even if you can
                string spotifyPlaylistName = null;
                if (includeFoldersInPlaylistName)
                {
                    spotifyPlaylistName = playlist.Name;
                }
                else
                {
                    spotifyPlaylistName = playlist.Name.Split('\\').Last();
                }

                if (includeZAtStartOfDatePlaylistName)
                {
                    // if it starts with a 2, it's a date playlist
                    if (spotifyPlaylistName.StartsWith("2"))
                    {
                        spotifyPlaylistName = $"Z {spotifyPlaylistName}";
                    }
                }

                // If Spotify playlist with same name already exists, clear it.
                // Otherwise create one
                SimplePlaylist thisPlaylist = Playlists.FirstOrDefault(p => p.Name == spotifyPlaylistName);
                string         thisPlaylistId;
                if (thisPlaylist != null)
                {
                    var request = new PlaylistReplaceItemsRequest(new List <string>()
                    {
                    });
                    var success = await Spotify.Playlists.ReplaceItems(thisPlaylist.Id, request);

                    if (!success)
                    {
                        Log("Error while trying to clear playlist before syncing new tracks");
                        return(errors);
                    }
                    thisPlaylistId = thisPlaylist.Id;
                }
                else
                {
                    var          request     = new PlaylistCreateRequest(spotifyPlaylistName);
                    FullPlaylist newPlaylist = await Spotify.Playlists.Create(Profile.Id, request);

                    thisPlaylistId = newPlaylist.Id;
                }


                List <FullTrack> songsToAdd = new List <FullTrack>();
                // And get the title and artist of each file, and add it to the GMusic playlist
                foreach (var song in playlist.Songs)
                {
                    string title  = song.Title;
                    string artist = song.Artist;
                    string album  = song.Album;

                    string         artistEsc = EscapeChar(artist.ToLower());
                    string         titleEsc  = EscapeChar(title.ToLower());
                    string         searchStr = $"artist:{artistEsc} track:{titleEsc}";
                    var            request   = new SearchRequest(SearchRequest.Types.Track, searchStr);
                    SearchResponse search    = await Spotify.Search.Item(request);

                    if (search.Tracks == null || search.Tracks.Items == null)
                    {
                        Log($"Could not find track on Spotify '{searchStr}' for '{title}' by '{artist}'");
                        continue;
                    }

                    if (search.Tracks.Items.Count == 0)
                    {
                        Log($"Found 0 results on Spotify for: {searchStr} for '{title}' by '{artist}'");
                        continue;
                    }

                    // try to find track matching artist and title
                    FullTrack trackToAdd = null;
                    foreach (FullTrack track in search.Tracks.Items)
                    {
                        bool titleMatches  = (track.Name.ToLower() == title.ToLower());
                        bool artistMatches = (track.Artists.Exists(a => a.Name.ToLower() == artist.ToLower()));
                        bool albumMatches  = (track.Album.Name.ToLower() == album.ToLower());
                        if (titleMatches && artistMatches && albumMatches)
                        {
                            trackToAdd = track;
                            break;
                        }
                        else if ((titleMatches && artistMatches) || (titleMatches && albumMatches) || (artistMatches && albumMatches))
                        {
                            // if two of them match, guessing this track is correct is
                            // probably better than just using the firstordefault, but keep looping hoping for a better track
                            trackToAdd = track;
                        }
                        else if (artistMatches && trackToAdd == null)
                        {
                            // if just the artist matches and we haven't found anything yet... this might be our best guess
                            trackToAdd = track;
                        }
                    }

                    if (trackToAdd == null)
                    {
                        trackToAdd = search.Tracks.Items.FirstOrDefault();
                        Log($"Didn't find a perfect match for {searchStr} for '{title}' by '{artist}', so using '{trackToAdd.Name}' by '{trackToAdd.Artists.FirstOrDefault().Name}' instead");
                    }

                    songsToAdd.Add(trackToAdd);
                }

                List <string> uris = songsToAdd.ConvertAll(x => x.Uri);
                while (uris.Count > 0)
                {
                    List <string> currUris = uris.Take(75).ToList();
                    if (currUris.Count == 0)
                    {
                        break;
                    }

                    uris.RemoveRange(0, currUris.Count);
                    var request = new PlaylistAddItemsRequest(currUris);
                    var resp    = await Spotify.Playlists.AddItems(thisPlaylistId, request);

                    if (resp == null)
                    {
                        Log("Error while trying to update playlist with track uris");
                        return(errors);
                    }
                }
            }

            return(errors);
        }
예제 #26
0
        private static async void ChooseMusicMood(SpotifyWebAPI api)
        {
            PrivateProfile profile = await api.GetPrivateProfileAsync();

            string name = string.IsNullOrEmpty(profile.DisplayName) ? profile.Id : profile.DisplayName;



            Console.WriteLine($"Hello there, {name}!");



            Console.WriteLine("Your playlists:");

            Paging <SimplePlaylist> playlists = await api.GetUserPlaylistsAsync(profile.Id);

            //do
            //{
            playlists.Items.ForEach(playlist =>
            {
                Console.WriteLine($"- {playlist.Name}");
            });

            PlaybackContext context = api.GetPlayback();

            if (context.IsPlaying)
            {
                Console.WriteLine($"You are listening {context.Item.Name}!");
            }

            Console.WriteLine("do you want to listen to music related to your mood ? (yes/no)");



            while (true)
            {
                string risposta = Console.ReadLine();

                if (risposta.Equals("Y") || risposta.Equals("yes") || risposta.Equals("y") || risposta.Equals("YES"))
                {
                    Console.WriteLine("Yes");
                    List <FullPlaylist> Playlists = new List <FullPlaylist>();
                    Console.WriteLine("choose your playlists to play according to your mood.");
                    Thread.Sleep(2000);
                    Console.WriteLine("type 1 to use default playlists ");
                    Console.WriteLine("type 2 to load your own playlists");
                    Console.WriteLine("type 3 to create your own playlists");


                    //string line = Console.ReadLine();
                    // switch (line)
                    //{


                    // case "1":
                    //    Playlists = PlayMusic.GetPlaylists(api);
                    //    Console.WriteLine("press enter when you are ready");
                    //    Console.ReadLine();
                    //    break;


                    //case "2":
                    //Console.WriteLine("Please enter the Uri of yours playlists you want to load");
                    //Playlists = PlayMusic.LoadPlaylists(api);
                    //        Console.WriteLine("press enter when you are ready");
                    //        Console.ReadLine();
                    //        break;


                    //    case "3":
                    //        Playlists = PlayMusic.CreatePLaylists(api);
                    //        Console.WriteLine("press enter when you are ready");
                    //        Console.ReadLine();
                    //        break;

                    //    default:
                    //        Console.WriteLine("Enter 1 2 or a 3");
                    //        break;


                    //}



                    while (true)

                    {
                        string mode = Console.ReadLine();

                        if (mode.Equals("1"))
                        {
                            Playlists = PlayMusic.GetPlaylists(api);

                            break;
                        }

                        else if (mode.Equals("2"))
                        {
                            Console.WriteLine("Please enter the Uri of yours playlists you want to load");
                            Playlists = PlayMusic.LoadPlaylists(api);

                            break;
                        }

                        else if (mode.Equals("3"))
                        {
                            Playlists = PlayMusic.CreatePLaylists(api);

                            break;
                        }
                        else
                        {
                            Console.WriteLine("Enter 1,2 or 3 please");
                        }
                    }



                    FullPlaylist PlaylistMood = PlayMusic.GetPlaylistMood(Playlists);
                    Console.WriteLine("Let's me choose a song for you:");
                    PlayMusic.ChangePlayback(api, PlaylistMood);
                    PlaybackContext context2 = api.GetPlayback();

                    Console.WriteLine($"You are listening {context2.Item.Name} now!");

                    PlayMusic.ManagePlayback(api);



                    Thread.Sleep(1000);

                    //Prog.Unsubscribe();



                    break;
                }
                else if (risposta.Equals("N") || risposta.Equals("NO") || risposta.Equals("n") || risposta.Equals("no"))
                {
                    Console.WriteLine("No");
                    Console.WriteLine("Ok, enjoy your song ");
                    break;
                }

                else
                {
                    Console.WriteLine("Enter yes or no please");
                }
            }



            Console.WriteLine("Thanks for trying the App");
        }
예제 #27
0
        public ErrorResponse CreatePlaylist(string userId, string name, List <FullTrack> songs, bool?isPrivate, bool?isLiked)
        {
            FullPlaylist playlist = _spotify.CreatePlaylist(userId, name, !isPrivate.GetValueOrDefault());

            return(AddTracks(playlist.Id, songs, isLiked.GetValueOrDefault()));
        }
예제 #28
0
        private async void execMethod(string cmd, string obj)
        {
            if (cmd == "open" && !SpotifyLocalAPI.IsSpotifyRunning()) // Start Spotify
            {
                Console.WriteLine("Abrir Spotify");
                SpotifyLocalAPI.RunSpotify();
                SpotifyLocalAPI.RunSpotifyWebHelper();
                Connect();
                AuthConnect();
                t.Speak("O que queres ouvir?");
            }

            if (SpotifyLocalAPI.IsSpotifyRunning())
            {
                if (cmd == "pause") // Pausar
                {
                    Console.WriteLine("Pausa");
                    await _spotify.Pause();

                    t.Speak("Estarei aqui à tua espera.");
                }

                if (cmd == "play") // Retomar
                {
                    Console.WriteLine("Retomar");
                    await _spotify.Play();
                }

                if (cmd == "mute") // Silenciar
                {
                    Console.WriteLine("Silenciar");
                    _spotify.Mute();
                    t.Speak("Já podes atender.");
                }

                if (cmd == "unmute") // Volume
                {
                    Console.WriteLine("Volume");
                    _spotify.UnMute();
                }


                if (cmd == "volumeUp") // Aumentar volume
                {
                    Console.WriteLine("Aumentar volume");
                    _spotify.SetSpotifyVolume(PostureVerify.getVol() + 25);
                }

                if (cmd == "volumeDown") // Diminuir volume
                {
                    Console.WriteLine("Dimiuir volume");
                    _spotify.SetSpotifyVolume(PostureVerify.getVol() - 25);
                }

                if (cmd == "close") // Fechar Spotify
                {
                    Console.WriteLine("Fechar");
                    SpotifyLocalAPI.StopSpotify();
                    t.Speak("Obrigado pela tua preferência. Até à próxima!");
                }

                if (cmd == "createList") // Criar lista de reprodução
                {
                    String name = obj;
                    Console.WriteLine("Criar lista de reprodução");
                    FullPlaylist playlist = _spotifyWeb.CreatePlaylist(id, name);
                    if (!playlist.HasError())
                    {
                        Console.WriteLine("Playlist-URI:" + playlist.Uri);
                    }

                    t.Speak("Lista de reprodução " + name + " criada com sucesso");
                }

                if (cmd == "addList") // Adicionar à lista de reprodução
                {
                    String name = obj;
                    Console.WriteLine("Adicionar à lista de reprodução");
                    String uri = _spotify.GetStatus().Track.TrackResource.Uri;
                    List <SimplePlaylist> playlist = _spotifyWeb.GetUserPlaylists(id).Items;
                    int index = playlist.FindIndex(x => x.Name == name);
                    _spotifyWeb.AddPlaylistTrack(id, _spotifyWeb.GetUserPlaylists(id).Items[index].Id, uri);
                    t.Speak("Música adicionada com sucesso!");
                }

                if (cmd == "removeList") // Remover música da lista de reprodução
                {
                    Console.WriteLine("Remover música da lista de reprodução");
                    String uri      = _spotify.GetStatus().Track.TrackResource.Uri;
                    String playlist = _spotifyWeb.GetUserPlaylists(id).Items[0].Id;
                    _spotifyWeb.RemovePlaylistTrack(id, playlist, new DeleteTrackUri(uri));
                    t.Speak("Música removida!");
                }

                if (cmd == "identify") // Reconhecer música actual
                {
                    Console.WriteLine("Não me lembro do nome desta música");
                    String name = _spotify.GetStatus().Track.TrackResource.Name;
                    t.Speak("A música que estás a ouvir é" + name);
                }


                if (cmd == "playMusic") // Ouvir música
                {
                    SearchType search_type = SearchType.Track;
                    SearchItem item;
                    String     musica;

                    musica = obj;
                    Console.WriteLine("Ouvir " + musica + "!");
                    item = _spotifyWeb.SearchItems(musica, search_type, 1, 0, "pt");
                    await _spotify.PlayURL(item.Tracks.Items[0].Uri, "");
                }

                if (cmd == "playAlbum") // Ouvir álbum
                {
                    SearchType search_type = SearchType.Album;
                    SearchItem item;
                    String     album;

                    album = obj;
                    Console.WriteLine("Ouvir " + album + "!");
                    item = _spotifyWeb.SearchItems(album, search_type, 1, 0, "pt");
                    await _spotify.PlayURL(item.Albums.Items[0].Uri, "");
                }

                if (cmd == "playArtist") // Ouvir artista
                {
                    SearchType search_type = SearchType.Track;
                    SearchItem item;
                    String     artist;

                    artist = obj;
                    Console.WriteLine("Ouvir " + artist + "!");
                    item = _spotifyWeb.SearchItems(artist, search_type, 1, 0, "pt");
                    await _spotify.PlayURL(item.Artists.Items[0].Uri, "");
                }
            }
            else
            {
                t.Speak("Spotify não está aberto.");
            }
        }
예제 #29
0
    public void GetRecommendations()
    {
        Debug.Log("GetRecommendations called");
        if (activeSeeds.Count > 0)
        {
            artistIds = new List <string>();
            trackIds  = new List <string>();

            foreach (var seed in activeSeeds)
            {
                if (seed != null)
                {
                    PlaylistScript playlistScript = seed.GetComponent <VinylScript>().playlistScript;
                    if (playlistScript.trackType == PlaylistScript.TrackType.artist)
                    {
                        if (playlistScript.artistId != null && playlistScript.artistId != "")
                        {
                            artistIds.Add(playlistScript.artistId);
                        }
                        else
                        {
                            Debug.LogError("artistId null/empty");
                        }
                    }
                    else if (playlistScript.trackType == PlaylistScript.TrackType.playlist)
                    {
                        if (playlistScript.ownerId != null && playlistScript.ownerId != "" && playlistScript.playlistId != null && playlistScript.playlistId != "")
                        {
                            FullPlaylist fullPlaylist = spotifyManagerScript.GetPlaylist(playlistScript.ownerId, playlistScript.playlistId);
                            artistIds.Add(fullPlaylist.Tracks.Items[0].Track.Artists[0].Id);
                        }
                        else
                        {
                            Debug.LogError("ownerId or playlistId null/empty");
                        }
                    }
                    else if (playlistScript.trackType == PlaylistScript.TrackType.track)
                    {
                        if (playlistScript.trackId != null && playlistScript.trackId != "")
                        {
                            trackIds.Add(playlistScript.trackId);
                        }
                        else
                        {
                            Debug.LogError("trackId null/empty");
                        }
                    }
                    else if (playlistScript.trackType == PlaylistScript.TrackType.album)
                    {
                        if (playlistScript.albumId != null && playlistScript.albumId != "")
                        {
                            FullAlbum fullAlbum = spotifyManagerScript.GetAlbum(playlistScript.albumId);
                            artistIds.Add(fullAlbum.Artists[0].Id);
                        }
                        else
                        {
                            Debug.LogError("albumId null/empty");
                        }
                    }
                    else
                    {
                        Debug.LogError("Unsupported track type");
                    }
                }

                if (artistIds.Count != 0)
                {
                    StartCoroutine(userRecommendations.LoadUserRecommendationsWithArtist(artistIds));
                }
                else if (trackIds.Count != 0)
                {
                    StartCoroutine(userRecommendations.LoadUserRecommendationsWithTrack(trackIds));
                }
                else
                {
                    Debug.LogError("Seed Id list is empty");
                }
            }
        }
    }
예제 #30
0
        public static FullPlaylist CreatePlaylist(SpotifyWebAPI api, String name)
        {
            PrivateProfile profile = api.GetPrivateProfile();

            string id = profile.Id;


            FullPlaylist playlist = api.CreatePlaylist(id, name);

            Thread.Sleep(3000);



            while (true)
            {
                Console.WriteLine("Enter keyword to find a song, enter finish when you have done your playlist");
                string risposta = Console.ReadLine();
                if (risposta.Equals("finish"))
                {
                    Console.WriteLine("Your playlist is create and save");
                    break;
                }
                else
                {
                    if (api.SearchItems(risposta, SpotifyAPI.Web.Enums.SearchType.Track) == null)
                    {
                        Console.WriteLine("No Song found, enter an other keyword");
                        Thread.Sleep(3000);
                    }
                    else
                    {
                        SearchItem         search    = api.SearchItems(risposta, SpotifyAPI.Web.Enums.SearchType.Track);
                        Paging <FullTrack> ListTrack = search.Tracks;
                        int count = 0;
                        ListTrack.Items.ForEach(track =>
                        {
                            Console.WriteLine($"-{count}  {track.Name} by {track.Artists[0].Name}");

                            count++;
                        });

                        Console.WriteLine($"enter the number of the song you want to add to your playlist {name}");

                        while (true)
                        {
                            int song = Convert.ToInt32(Console.ReadLine());
                            if (song <= ListTrack.Items.Count)
                            {
                                api.AddPlaylistTrack(playlistId: playlist.Id, uri:  ListTrack.Items[song].Uri);
                                break;
                            }

                            else
                            {
                                Console.WriteLine("the number entered does not match any proposed music, please enter a correct number");
                            }
                        }
                    }
                }
            }

            return(playlist);
        }