예제 #1
0
        public async Task <List <PlaylistOverview> > GetAllByUserIdAsync(string userId)
        {
            if (string.IsNullOrWhiteSpace(userId))
            {
                return(new List <PlaylistOverview>());
            }

            User user = await _userRepo.GetByIdAsync(userId);

            List <PlaylistDefinition> definitions = await _playlistDefRepo.GetAllByUserIdAsync(user.Id);

            ISpotifyClient client = await _spotifyClientFactory.CreateClientAsync(user.RefreshToken);

            return(await definitions
                   .ToAsyncEnumerable()
                   .SelectAwait(async o => new
            {
                Def = o,
                Playlist = await client.Playlists.Get(o.TargetPlaylistId)
            })
                   .Select(o => new PlaylistOverview
            {
                Definition = o.Def,
                Name = o.Playlist.Name,
                Description = HttpUtility.HtmlDecode(o.Playlist.Description),
                IsGenerating = false,
                ErrorMessage = null
            })
                   .ToListAsync());
        }
예제 #2
0
 public SpottyApp(string clientId, string clientSecret, Uri redirectUrl, ISpotifyClient spotifyClient)
 {
     ClientId      = clientId;
     ClientSecret  = clientSecret;
     RedirectUrl   = redirectUrl;
     SpotifyClient = spotifyClient;
 }
    public ISpotifyClient GetSpotifyClient()
    {
        var clientInfo = new SpotifyClientInfo(
            EnvHelpers.GetEnvOrDefault("SPOTPG_SPOTIFY_CLIENT_ID", this.configuration.ClientId),
            EnvHelpers.GetEnvOrDefault("SPOTPG_SPOTIFY_CLIENT_SECRET", this.configuration.ClientSecret));

        if (this.client != null && this.currentInfo == clientInfo)
        {
            return(this.client);
        }

        this.serviceLogger.LogInfo("Recreation Spotify client...");

        var authResponse = new AuthorizationCodeTokenResponse
        {
            AccessToken  = this.configuration.AccessToken,
            RefreshToken = this.configuration.RefreshToken
        };

        var auth = new AuthorizationCodeAuthenticator(clientInfo.Id, clientInfo.Secret, authResponse);

        var config = SpotifyClientConfig.CreateDefault()
                     .WithDefaultPaginator(new SimplePaginator())
                     .WithRetryHandler(new SimpleRetryHandler())
                     .WithAuthenticator(auth);

        this.client      = new SpotifyClient(config);
        this.currentInfo = clientInfo;

        this.serviceLogger.LogInfo("New Spotify client was created successfully");

        return(this.client);
    }
예제 #4
0
        /// <summary>
        /// Lookup User Addable Playlists
        /// </summary>
        /// <param name="client">Spotify Sdk Client</param>
        /// <returns>List of Simplified Playlist</returns>
        public static async Task <List <SimplifiedPlaylist> > AuthLookupUserAddablePlaylistsAsync(
            this ISpotifyClient client)
        {
            var results = new List <SimplifiedPlaylist>();
            var user    = await client.AuthLookupUserProfileAsync();

            var playlists = await client.AuthLookupUserPlaylistsAsync();

            var loop = playlists?.Next != null;

            do
            {
                if (playlists?.Items != null)
                {
                    results.AddRange(playlists.Items.Where(w =>
                                                           w.Collaborative ||
                                                           w.Owner.Id == user.Id));
                }
                if (playlists?.Next != null)
                {
                    playlists = await client.AuthGetAsync <CursorPaging <SimplifiedPlaylist> >(
                        new Uri(playlists.Next));
                }
                else
                {
                    loop = false;
                }
            }while (loop);
            return(results);
        }
        public void Init()
        {
            // Configuration
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            IConfiguration config = configBuilder.Build();

            // Spotify Client Factory
            _client = SpotifyClientFactory.CreateSpotifyClient(
                config["client_id"], config["client_secret"]);
            Assert.IsNotNull(_client);
            // Spotify Client Token
            var accessToken = new AccessToken()
            {
                Token      = config["token"],
                Refresh    = config["refresh"],
                Expiration = DateTime.Parse(config["expires"]),
                TokenType  = (TokenType)Enum.Parse(typeof(TokenType), config["type"])
            };
            var expired = DateTime.UtcNow > accessToken.Expiration;

            Assert.IsFalse(expired);
            _client.SetToken(accessToken);
        }
예제 #6
0
        public BuffersWindow()
        {
            // language stuff needs to happen before InitializeComponent
            if (!settings.DontShowFirstTimeWizard)
            {
                // find out what language was used in the installer and use it for the first time wizard and everything else
                SetThreadToInstallationLanguage();
                DisplayFirstTimeWizard();
            }
            else
            {
                // if a language code is set in settings, set it on the thread
                if (settings.UILanguageCode != 0)
                {
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(settings.UILanguageCode);
                }
            }
            InitializeComponent();
            InitializeTrayIcon();
            Commands                 = new Dictionary <string, HotkeyCommandBase>();
            playbackManager          = new PlaybackManager(settings.OutputDeviceID, settings.UseDirectSound);
            playbackManager.OnError += new PlaybackManager.PlaybackManagerErrorHandler(StreamingError);

            SetupFormEventHandlers();
            Buffers          = new BufferListCollection();
            _playQueueBuffer = new BufferList("Play Queue", false);
            Buffers.Add(_playQueueBuffer);
            Buffers.Add(new PlaylistContainerBufferList("Playlists", false));
            spotify = SpotifyClient.Instance;
            _trayIconMenuManager      = new TrayIconMenuManager(Buffers, Commands, _trayIcon);
            settings.PropertyChanged += new PropertyChangedEventHandler(OnUserSettingChange);
        }
 public async Task AddTrackToPlaylist(ISpotifyClient spotifyClient, Track track)
 {
     // Add the track to the playlist.
     await spotifyClient.Playlists.AddItems(track.PlaylistId, new PlaylistAddItemsRequest(new List <string>
     {
         $"{_trackInlineBaseUri}{track.Id}"
     }));
 }
예제 #8
0
        private async Task RemoveTrack(ISpotifyClient spotifyClient, Track track)
        {
            // Mark the track as removed and save it.
            track.State = TrackState.RemovedByDownvotes;

            await _trackRepository.Upsert(track);

            // Remove the track from the spotify playlist.
            await _spotifyClientService.RemoveTrackFromPlaylist(spotifyClient, track.Id, track.PlaylistId);
        }
 private Task <FullPlaylist> GetPlaylistFromApi(ISpotifyClient spotifyClient, string playlistId)
 {
     try
     {
         return(spotifyClient.Playlists.Get(playlistId));
     }
     catch (APIException exception)
     {
         SentrySdk.CaptureException(exception);
         return(null);
     }
 }
예제 #10
0
 public async Task <PublicUser> GetPublicUser(string id, ISpotifyClient client)
 {
     try
     {
         var publicUserProfile = client.UserProfile.Get(id);
         return(await publicUserProfile);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
예제 #11
0
        /// <summary>
        /// Add the track to the playlist.
        /// </summary>
        private async Task AddTrack(ISpotifyClient spotifyClient, Bot.Users.User user, Track newTrack, string playlistId)
        {
            newTrack.PlaylistId            = playlistId;
            newTrack.CreatedAt             = DateTimeOffset.UtcNow;
            newTrack.AddedByTelegramUserId = user.Id;
            newTrack.State = TrackState.AddedToPlaylist;

            // Add the track to the playlist.
            await _trackRepository.Upsert(newTrack);

            await _spotifyClientService.AddTrackToPlaylist(spotifyClient, newTrack);
        }
예제 #12
0
 public async Task <PrivateUser> GetAllInformation(ISpotifyClient client)
 {
     try
     {
         var userInfo = client.UserProfile.Current();
         return(await userInfo);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
예제 #13
0
 private async Task <FullTrack> GetTrackFromApi(ISpotifyClient spotifyClient, string trackId)
 {
     try
     {
         return(await spotifyClient.Tracks.Get(trackId));
     }
     catch (APIException exception)
     {
         SentrySdk.CaptureException(exception);
         return(null);
     }
 }
예제 #14
0
        public async Task <List <SimplePlaylist> > GetPublicUserPlayLists(string id, ISpotifyClient client)
        {
            try
            {
                var publicUserPlayLists = await client.Playlists.GetUsers(id);

                return(publicUserPlayLists.Items.ToList());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #15
0
        public async Task <FullTrack> GetTrack(string id, ISpotifyClient client)
        {
            try
            {
                var track = client.Tracks.Get(id);

                return(await track);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #16
0
        public async Task <FullPlaylist> GetPlayList(string id, ISpotifyClient client)
        {
            try
            {
                var playList = await client.Playlists.Get(id);

                return(playList);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #17
0
        public async Task <bool> ResumeCurrentPlayBack(ISpotifyClient client)
        {
            try
            {
                var resumeCurrent = await client.Player.ResumePlayback();

                return(resumeCurrent);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #18
0
        public async Task <bool> SkipPreviousItem(ISpotifyClient client)
        {
            try
            {
                var skipPrev = await client.Player.SkipPrevious();

                return(skipPrev);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #19
0
 /// <summary>
 /// Refreshes Spotify authentication to continue having access to Spotify music controls
 /// </summary>
 /// <returns>Task for refreshing token</returns>
 private async Task RefreshAuthentication()
 {
     if (token == null)
     {
         await Task.Run(Init);
     }
     else if (token != null && token.IsExpired)
     {
         PKCETokenRefreshRequest refreshRequest  = new PKCETokenRefreshRequest("<INSERT_CLIENT_ID>", token.RefreshToken);
         PKCETokenResponse       refreshResponse = await new OAuthClient().RequestToken(refreshRequest);
         client = new SpotifyClient(refreshResponse.AccessToken);
     }
 }
예제 #20
0
        public async Task <List <SimpleAlbum> > GetArtistAlbums(string id, ISpotifyClient client)
        {
            try
            {
                var artistAlbums = await client.Artists.GetAlbums(id);

                return(artistAlbums.Items.ToList());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #21
0
        public async Task <FullArtist> GetArtist(string id, ISpotifyClient client)
        {
            try
            {
                var artist = client.Artists.Get(id);

                return(await artist);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #22
0
        public void Init()
        {
            // Configuration
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            IConfiguration config = configBuilder.Build();

            // Spotify Client Factory
            _client = SpotifyClientFactory.CreateSpotifyClient(
                config["client_id"], config["client_secret"]);
            Assert.IsNotNull(_client);
        }
예제 #23
0
        public async Task <List <SimplePlaylist> > GetUserPlayLists(ISpotifyClient client)
        {
            try
            {
                var playLists = await client.Playlists.CurrentUsers();

                return(playLists.Items.ToList());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #24
0
        public async Task <DeviceResponse> GetAvailableDevices(ISpotifyClient client)
        {
            try
            {
                var device = await client.Player.GetAvailableDevices();

                return(device);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #25
0
        /// <summary>
        /// Completes the Spotify authorization process
        /// </summary>
        public async Task Init()
        {
            var(v, c) = PKCEUtil.GenerateCodes();
            await server.Start();

            challenge = (v, c).c;
            verifier  = (v, c).v;

            server.AuthorizationCodeReceived += async(sender, response) =>
            {
                await server.Stop();

                token = await new OAuthClient().RequestToken(
                    new PKCETokenRequest("<INSERT_CLIENT_ID>", response.Code, server.BaseUri, verifier));
                client          = new SpotifyClient(token);
                IsAuthenticated = true;
                bool hasPremium = await HasPremium();

                MessagingCenter.Send(new SpotifyLoginMessage("LoginSuccess", hasPremium), "LoginSuccess");
            };

            var loginRequest = new LoginRequest(
                new Uri("http://localhost:5000/callback"),
                "<INSERT_CLIENT_ID>",
                LoginRequest.ResponseType.Code)
            {
                CodeChallengeMethod = "S256",
                CodeChallenge       = challenge,
                Scope = new[]
                {
                    Scopes.UserModifyPlaybackState,
                    Scopes.AppRemoteControl,
                    Scopes.UserReadCurrentlyPlaying,
                    Scopes.UserReadPlaybackState,
                    Scopes.UserLibraryRead,
                    Scopes.UserReadRecentlyPlayed,
                    Scopes.UserReadPrivate,
                },
            };

            var uri = loginRequest.ToUri();

            try
            {
                await Browser.OpenAsync(uri, BrowserLaunchMode.SystemPreferred);
            }
            catch (Exception)
            {
                // TODO: log error to app center.
            }
        }
예제 #26
0
        public async Task <FullAlbum> GetTrackAlbum(string albumId, ISpotifyClient client)
        {
            try
            {
                var trackAlbum = client.Albums.Get(albumId);


                return(await trackAlbum);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #27
0
        public async Task <bool> AddToQueue
            (ISpotifyClient client, PlayerAddToQueueRequest request)
        {
            try
            {
                var addToQueue = await client.Player.AddToQueue(request);

                return(addToQueue);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #28
0
        public async Task <CurrentlyPlaying> GetCurrentlyPlayingItem
            (ISpotifyClient client, PlayerCurrentlyPlayingRequest request)
        {
            try
            {
                var currentPlaying = await client.Player.GetCurrentlyPlaying(request);

                return(currentPlaying);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #29
0
        public async Task <List <SimpleAlbum> > GetNewReleases(ISpotifyClient client)
        {
            try
            {
                var newReleases = await client.Browse.GetNewReleases();

                var res = newReleases.Albums.Items.ToList();

                return(res);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #30
0
        public async Task <List <FullArtist> > GetUserTopArtists(ISpotifyClient client)
        {
            try
            {
                var userTopArtists = await client.Personalization.GetTopArtists();

                var userTopArtistsList = userTopArtists.Items.ToList();

                return(userTopArtistsList);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }