Exemplo n.º 1
0
        private void Resume()
        {
            avaiability(async() =>
            {
                playback = await SpotifyApi.GetPlaybackAsync();

                if (playback.Context != null || playback.Item != null)
                {
                    if (playback.IsPlaying)
                    {
                        PlayerImage     = "ic_action_play.png";
                        ErrorResponse x = await SpotifyApi.PausePlaybackAsync();
                    }
                    else
                    {
                        PlayerImage     = "ic_action_pause.png";
                        ErrorResponse x = await SpotifyApi.ResumePlaybackAsync(playback.Device.Id, string.Empty,
                                                                               new List <string>()
                        {
                            playback.Item.Uri
                        }, "", playback.ProgressMs);
                    }
                }
            });
        }
Exemplo n.º 2
0
        public Lobby()
        {
            InitializeComponent();

            _spotifyApi = new SpotifyApi();
            _user       = _spotifyApi.GetUser();
        }
Exemplo n.º 3
0
        public ExportPlaylist(SpotifyApi _spotifyApi)
        {
            InitializeComponent();

            spotifyApi = _spotifyApi;
            Task.Run(() => RunView()).Wait();
        }
Exemplo n.º 4
0
        public R <IList <AudioResource>, LocalStr> Search(ResolveContext ctx, string keyword)
        {
            var searchResult = api.Request(() => api.Client.Search.Item(
                                               new SearchRequest(SearchRequest.Types.Track, keyword))
                                           );


            if (!searchResult.Ok)
            {
                return(searchResult.Error);
            }

            if (searchResult.Value.Tracks.Total > SearchLimit)
            {
                return(new LocalStr("Too many search results, please make your search query more specific."));
            }

            var pagesTask = api.Client.PaginateAll(searchResult.Value.Tracks, (s) => s.Tracks);

            var pagesTaskResolveResult = api.ResolveRequestTask(pagesTask);

            if (!pagesTaskResolveResult.Ok)
            {
                return(pagesTaskResolveResult.Error.Item2);
            }

            var result = new List <AudioResource>();

            foreach (var item in pagesTask.Result)
            {
                result.Add(new AudioResource(item.Uri, SpotifyApi.TrackToName(item), ResolverFor));
            }

            return(result);
        }
Exemplo n.º 5
0
        public R <PlayResource, LocalStr> GetResource(ResolveContext ctx, string uriOrUrl)
        {
            string uri;

            // Convert if it is a URL.
            var uriResult = SpotifyApi.UrlToUri(uriOrUrl);

            if (uriResult.Ok)
            {
                uri = uriResult.Value;
            }
            else
            {
                uri = uriOrUrl;
            }

            var trackOption = api.UriToTrack(uri);

            if (!trackOption.Ok)
            {
                return(trackOption.Error);
            }

            var resource = new AudioResource(uri, SpotifyApi.TrackToName(trackOption.Value), ResolverFor);

            return(new PlayResource(resource.ResourceId, resource));
        }
Exemplo n.º 6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "callback")] HttpRequest req,
            [Table(
                 TableConstants.AuthorizeStateTable,
                 Connection = Constants.StorageConnection
                 )] CloudTable authorizeTable,
            [Table(
                 TableConstants.UserTable,
                 Connection = Constants.StorageConnection
                 )] CloudTable userTable,
            ILogger log)
        {
            await authorizeTable.CreateIfNotExistsAsync();

            await userTable.CreateIfNotExistsAsync();

            string code  = req.Query["code"];
            string error = req.Query["error"];
            string state = req.Query["state"];

            if (!string.IsNullOrWhiteSpace(error))
            {
                log.LogError("Received error from Spotify authorization: {Error}", error);
                return(new BadRequestResult());
            }

            var getAuthorizedOperation = TableOperation.Retrieve <AuthorizeEntity>(TableConstants.AuthorizePartitionKey, state);

            var result = await authorizeTable.ExecuteAsync(getAuthorizedOperation);

            var entity = result.Result as AuthorizeEntity;

            if (entity == null)
            {
                log.LogError("Could not find associated authorize entity. Callback may have been called twice.");
                return(new NotFoundResult());
            }

            var deleteAuthorizeOperation = TableOperation.Delete(entity);
            await authorizeTable.ExecuteAsync(deleteAuthorizeOperation);

            var tokenResponse = await SpotifyApi.FinishAuthorizeAsync(code, $"{req.Scheme}://{req.Host}/api/callback");

            var spotifyUserInfo = await SpotifyApi.GetUserInfoAsync(tokenResponse.access_token);

            var user = UserEntity.Map(spotifyUserInfo);

            var repo = new UserRepository(userTable);
            await repo.AddUser(user);

            await SecretRepository.SaveToken(user.RowKey, new TokenSecrets
            {
                AccessToken  = tokenResponse.access_token,
                RefreshToken = tokenResponse.refresh_token,
                ExpiresInUtc = DateTime.UtcNow.AddSeconds(tokenResponse.expires_in)
            });

            return(new RedirectResult("/"));
        }
Exemplo n.º 7
0
 public PlaylistMenuFunctions(TracksConverter tracksConverter, PlaylistsUtils playlistsUtils, TrackMenuFunctions trackMenuFunctions, ExitFunctions exitFunctions, SpotifyApi spotifyApi)
 {
     _tracksConverter    = tracksConverter;
     _playlistsUtils     = playlistsUtils;
     _trackMenuFunctions = trackMenuFunctions;
     _exitFunctions      = exitFunctions;
     _spotifyApi         = spotifyApi;
 }
Exemplo n.º 8
0
        public async Task <Playlist> CopyPlaylist(Models.PlaylistRequest request)
        {
            var playlist  = Playlists.First(t => t.Id == request.PlaylistId);
            var savedCopy = await _spotifyWebApi.CreatePlaylist(playlist, SpotifyApi.Playlists(Me), Token);

            Playlists.Add(savedCopy);
            return(savedCopy);
        }
        public async Task <IActionResult> PlayLists()
        {
            var envelope = await _spotify.Get <Envelope <Playlist> >(SpotifyApi.Playlists(_playlistManager.Me), _playlistManager.Token);

            _playlistManager.Reset();
            _playlistManager.Playlists.AddRange(envelope.Items);
            return(new OkObjectResult(_playlistManager.Playlists));
        }
Exemplo n.º 10
0
 public ResourceResolver(ConfFactories conf, SpotifyApi spotifyApi)
 {
     AddResolver(new MediaResolver());
     AddResolver(new YoutubeResolver(conf.Youtube));
     AddResolver(new SoundcloudResolver());
     AddResolver(new TwitchResolver());
     AddResolver(new BandcampResolver());
     AddResolver(new SpotifyResolver(spotifyApi));
 }
Exemplo n.º 11
0
 public AlbumMenuFunctions(AlbumsUtils albumsUtils, TracksConverter tracksConverter, ExitFunctions exitFunctions,
                           TrackMenuFunctions trackMenuFunctions, SpotifyApi spotifyApi)
 {
     _albumsUtils        = albumsUtils;
     _tracksConverter    = tracksConverter;
     _exitFunctions      = exitFunctions;
     _trackMenuFunctions = trackMenuFunctions;
     _spotifyApi         = spotifyApi;
 }
Exemplo n.º 12
0
 public ArtistMenuFunctions(ArtistsUtils artistsUtils, SpotifyApi spotifyApi, TracksGenerator tracksGenerator,
                            AlbumsGenerator albumsGenerator, ExitFunctions exitFunctions)
 {
     _artistsUtils    = artistsUtils;
     _spotifyApi      = spotifyApi;
     _tracksGenerator = tracksGenerator;
     _albumsGenerator = albumsGenerator;
     _exitFunctions   = exitFunctions;
 }
Exemplo n.º 13
0
        public MatchCertainty MatchResource(ResolveContext ctx, string uri)
        {
            if (SpotifyApi.UriToTrackId(uri).Ok || SpotifyApi.UrlToTrackId(uri).Ok)
            {
                return(MatchCertainty.Always);
            }

            return(MatchCertainty.Never);
        }
Exemplo n.º 14
0
        private void Forward()
        {
            avaiability(async() =>
            {
                playback = await SpotifyApi.GetPlaybackAsync();

                if (playback.Context != null || playback.Item != null)
                {
                    ErrorResponse x = await SpotifyApi.ResumePlaybackAsync(playback.Device.Id, string.Empty,
                                                                           new List <string>()
                    {
                        playback.Item.Uri
                    }, "", playback.ProgressMs + 10000);
                }
            });
        }
Exemplo n.º 15
0
        public async Task AddTracks(AddTracksRequest requestedTracks, string token)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, SpotifyApi.PlaylistTracks(requestedTracks.PlaylistId));

            request.Headers.Add("Authorization", $"Bearer {token}");
            request.Content = new StringContent(JsonSerializer.Serialize(requestedTracks.Tracks));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var client   = _httpClient.CreateClient();
            var response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                var error = new Exception($"Add tracks failed with: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
                _logger.Error(error, string.Empty);
                throw error;
            }
        }
Exemplo n.º 16
0
        public R <Uri, LocalStr> GetThumbnailUrl(ResolveContext ctx, PlayResource playResource)
        {
            var trackId = SpotifyApi.UriToTrackId(playResource.BaseData.ResourceId);

            if (!trackId.Ok)
            {
                return(trackId.Error);
            }

            var response = api.Request(() => api.Client.Tracks.Get(trackId.Value));

            if (!response.Ok)
            {
                return(response.Error);
            }

            return(new Uri(response.Value.Album.Images.OrderByDescending(item => item.Height).ToList()[0].Url));
        }
Exemplo n.º 17
0
        public static void Initialize(TestContext tc)
        {
            IO.WriteLine = _ => { };
            IO.Write     = _ => { };
            IO.ReadKey   = () => new ConsoleKeyInfo();
            IO.ReadLine  = () => "string";
            IO.Clear     = () => { };

            var a          = new SpotifyApi();
            var spotifyApi = new SpotifyApi {
                Spotify = Authorization.Authorize()
            };
            var privateProfile = spotifyApi.Spotify.GetPrivateProfile();

            spotifyApi.CurrentUserId = privateProfile.Id;

            SpotifyApi = spotifyApi;
        }
Exemplo n.º 18
0
        public async Task <ShuffleResponse> ShufflePlaylist(Models.PlaylistRequest request)
        {
            var copiedPlaylist = await CopyPlaylist(request);

            var tracks = await GetPlaylistTracks(request);

            await AddTracks(new AddTracksRequest { PlaylistId = copiedPlaylist.Id, Tracks = tracks.Select(t => t.Uri).Shuffle() });

            Reset();
            var envelope = await _spotifyWebApi.Get <Envelope <Playlist> >(SpotifyApi.Playlists(Me), Token);

            Playlists.AddRange(envelope.Items);
            tracks = await GetPlaylistTracks(new Models.PlaylistRequest {
                PlaylistId = copiedPlaylist.Id
            });

            return(new ShuffleResponse {
                PlaylistName = copiedPlaylist.Name, TracksAdded = tracks.Count()
            });
        }
Exemplo n.º 19
0
        private async void avaiability(Action action)
        {
            if (SpotifyApi != null)
            {
                if ((await SpotifyApi.GetDevicesAsync()).Devices.Count != 0)
                {
                    playback = await SpotifyApi.GetPlaybackAsync();

                    if (playback.CurrentlyPlayingType.Equals(TrackType.Track))
                    {
                        if (Logged)
                        {
                            if (playback.Item != null || playback.Item.Name != (await SpotifyApi.GetPlaybackAsync()).Item.Name)
                            {
                                action();
                            }
                            else
                            {
                                CrossToastPopUp.Current.ShowToastMessage("Errore durante il download del testo");
                            }
                        }
                        else
                        {
                            CrossToastPopUp.Current.ShowToastMessage("login richiesto");
                        }
                    }
                    else
                    {
                        CrossToastPopUp.Current.ShowToastMessage("Impossibile scaricare il testo, non è una canzone");
                    }
                }
                else
                {
                    CrossToastPopUp.Current.ShowToastMessage("Accedi a spotify da uno dei tuoi dispositivi!");
                }
            }
            else
            {
                CrossToastPopUp.Current.ShowToastMessage("Login Richiesto");
            }
        }
Exemplo n.º 20
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "authorize")] HttpRequest req,
            [Table(
                 TableConstants.AuthorizeStateTable,
                 Connection = Constants.StorageConnection
                 )] CloudTable table,
            ILogger log)
        {
            await table.CreateIfNotExistsAsync();

            var state = Guid.NewGuid().ToString();

            var operation = TableOperation.Insert(new AuthorizeEntity
            {
                PartitionKey = TableConstants.AuthorizePartitionKey,
                RowKey       = state
            });

            await table.ExecuteAsync(operation);

            return(new RedirectResult(SpotifyApi.StartAuthorizeRedirectUrl($"{req.Scheme}://{req.Host}/api/callback", state)));
        }
Exemplo n.º 21
0
        private async Task UpdateUI()
        {
            playback = await SpotifyApi.GetPlaybackAsync();

            AlbumName  = playback.Item.Album.Name;
            AlbumImage = playback.Item.Album.Images.FirstOrDefault().Url;
            TrackName  = playback.Item.Name;
            ArtistName = playback.Item.Artists.FirstOrDefault().Name;

            if (playback.IsPlaying)
            {
                PlayerImage = "ic_action_pause.png";
            }
            else
            {
                PlayerImage = "ic_action_play.png";
            }

            SetLyrics(playback.Item.Artists.FirstOrDefault().Name, playback.Item.Album.Name, playback.Item.Name);

            App.Mongo.UpdateMongoDbArtist(playback.Item.Artists.FirstOrDefault().Name, playback.Item.Album.Name, playback.Item.Name, Lyrics);
        }
        private async void TestAuth()
        {
            //Problemi
            // - funziona solo quando spotify è già in riproduzione
            // - funziona solo quando spotify è aperto in uno dei qualsiasi dispositivi a cui è collegato l'account

            // Istanzio qui il playback dato che ad ogni click deve scaricare le informazioni sul brano
            playback = await SpotifyApi.GetPlaybackAsync();

            if (playback.Context != null || playback.Item != null)
            {
                if (playback.IsPlaying)
                {
                    ErrorResponse x = await SpotifyApi.PausePlaybackAsync();
                }
                else
                {
                    ErrorResponse x = await SpotifyApi.ResumePlaybackAsync(playback.Device.Id, string.Empty,
                                                                           new List <string>() { playback.Item.Uri }, "", playback.ProgressMs);
                }
            }
        }
Exemplo n.º 23
0
        private static async Task <string> GetAccessToken(string userId)
        {
            TokenSecrets tokens = null;

            try
            {
                tokens = await SecretRepository.GetToken(userId);
            }
            catch (TokenExpiredException ex)
            {
                var tokenResponse = await SpotifyApi.RefreshTokenAsync(ex.RefreshToken);

                tokens = new TokenSecrets
                {
                    AccessToken  = tokenResponse.access_token,
                    RefreshToken = tokenResponse.refresh_token ?? ex.RefreshToken,
                    ExpiresInUtc = DateTime.UtcNow.AddSeconds(tokenResponse.expires_in)
                };

                await SecretRepository.SaveToken(userId, tokens);
            }

            return(tokens.AccessToken);
        }
Exemplo n.º 24
0
 public string RestoreLink(ResolveContext ctx, AudioResource resource)
 {
     return(SpotifyApi.UriToUrl(resource.ResourceId).OkOr(null));
 }
Exemplo n.º 25
0
        public Login()
        {
            InitializeComponent();

            _spotifyApi = new SpotifyApi();
        }
Exemplo n.º 26
0
 public SpotifyResolver(SpotifyApi api)
 {
     this.api = api;
 }
Exemplo n.º 27
0
        public LibrespotPlayer(SpotifyApi api, ConfLibrespot conf)
        {
            this.api  = api;
            this.conf = conf;
            state     = State.NotSetUp;
            Log.Trace("Changed librespot state to notsetup.");
            output = new List <string>();

            void Fail(string message)
            {
                Log.Error(message);
                state = State.NotSetUp;
                Log.Trace("Failed setup of librespot, changed state to notsetup.");
                if (process != null && !process.HasExitedSafe())
                {
                    process.Kill();
                }

                if (process != null)
                {
                    process.Close();
                    process = null;
                }
            }

            // Check if spotify is available.
            if (api.Client == null)
            {
                Fail($"Failed to setup Librespot: Spotify API access was not set up correctly. Cannot play from spotify.");
                return;
            }

            // Get device ID for librespot.
            // 1. Connect librespot for it to appear in the API.
            var processOption = LaunchLibrespot();

            if (!processOption.Ok)
            {
                Fail($"Failed to setup Librespot: {processOption.Error}");
                return;
            }

            // 2. Fetch device ID via API.
            var response = api.Request(() => api.Client.Player.GetAvailableDevices());

            if (!response.Ok)
            {
                Fail($"Failed to setup Librespot: Could not get device ID - {response.Error}.");
                return;
            }

            deviceId = "";
            foreach (var device in response.Value.Devices.Where(device => device.Name == conf.LibrespotDeviceName))
            {
                deviceId = device.Id;
            }

            // 3. Check for success.
            if (deviceId == "")
            {
                Fail("Failed to setup Librespot: Could not get device ID.");
                return;
            }

            // 4. Exit Librespot.
            process.Kill();
            process.Close();
            process = null;

            Log.Trace("Set up Librespot, changed state to idle.");
            state = State.Idle;
        }
Exemplo n.º 28
0
 public TracksUtils(TracksConverter tracksConverter, SpotifyApi spotifyApi)
 {
     _tracksConverter = tracksConverter;
     _spotifyApi      = spotifyApi;
 }
Exemplo n.º 29
0
        private async void getPlaylist()
        {
            //show progress indicator
            setProgressIndicator(true);
            SystemTray.ProgressIndicator.Text = "Getting your Tweet Mix";

            try
            {
                //set an int as the id
                int id = 0;
                //build twitter url
                string url = twitter.getUrl(username, apiAttempt);

                //call twitter vaI base api class, we only want the response code at this point
                string apiResponse = await twitter.Call(url);

                //if the response did not come back null or contain an error code
                if (apiResponse != null || apiResponse.Contains("Error: "))
                {
                    //use json.net to turn json into an opject
                    TwitterItems apiData = JsonConvert.DeserializeObject <TwitterItems>(apiResponse);

                    //loop through and set everything to the list
                    foreach (Status data in apiData.statuses)
                    {
                        PlayListItems items = new PlayListItems();
                        //add id to list
                        items.ID = id.ToString();
                        //add twitter details to list
                        items.Message      = data.text;
                        items.ProfileImage = data.user.profile_image_url;
                        items.Username     = data.user.name;
                        //go spilt the message via the Song class
                        Song song = spiltMessage(data.text);
                        //add those values to the list
                        items.ArtistName = song.Artist;
                        items.SongName   = song.Track;

                        //now we need the artowrk so go get it from spotify as its more reliable
                        SpotifyApi spotify = new SpotifyApi();
                        //build a url of the songname to go ask spotify for its details
                        string spotifySearchUrl = spotify.BuildSearchUrl(song.Track);

                        string response = await spotify.Call(spotifySearchUrl);

                        //add in method so that calls can be used again
                        if (response != null)
                        {
                            List <SpotifyItem> tracks         = new List <SpotifyItem>();
                            SpotifyItem        spotifyApiData = JsonConvert.DeserializeObject <SpotifyItem>(response);

                            //call the spotify embed api to go get artwork
                            string spotifyArtowrkUrl = spotify.buildEmbedUrl(spotifyApiData.tracks[0].href);
                            string artworkResponse   = await spotify.Call(spotifyArtowrkUrl);

                            SpotifyImageItems imageData = JsonConvert.DeserializeObject <SpotifyImageItems>(artworkResponse);
                            items.AlbumArtworkUrl = imageData.thumbnail_url;
                        }
                        Items.Add(items);
                        id++;
                    }
                }
                else if (apiResponse.Contains("Error: "))
                {
                    //lets go see what error it is
                    int errorCode = twitter.getCorrectError(apiResponse);
                    if (errorCode == 429 && apiAttempt < 3)
                    {
                        setProgressIndicator(false);
                        //call again;
                        callAgain();
                    }
                    else
                    {
                        string errorMessage = twitter.ErrorMesssage(errorCode);
                        showError(errorMessage);
                        callAgain();
                        setProgressIndicator(false);
                    }
                }
                setProgressIndicator(false);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Wifi is disabled in phone settings");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                setProgressIndicator(false);
                callAgain();
            }

            setDataContext();
        }
Exemplo n.º 30
0
 public TrackMenuFunctions(TracksUtils tracksUtils, ExitFunctions exitFunctions, SpotifyApi spotifyApi)
 {
     _tracksUtils   = tracksUtils;
     _exitFunctions = exitFunctions;
     _spotifyApi    = spotifyApi;
 }