Ejemplo n.º 1
0
        public async Task <SpotifyTrack> GetTrackById(string id)
        {
            var            track   = new SpotifyTrack();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://api.spotify.com/v1/tracks/" + id);

            request.Method      = "GET";
            request.KeepAlive   = true;
            request.ContentType = "appication/json";
            request.Headers.Add("Authorization", $"Bearer {(await GetToken()).AccessToken}");
            //request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
            string          myResponse = "";

            using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
            {
                myResponse = sr.ReadToEnd();
            }
            dynamic  obj    = JObject.Parse(myResponse);
            TimeSpan time   = TimeSpan.FromMilliseconds(Convert.ToDouble(obj?.duration_ms.ToString()));
            var      second = time.Seconds < 10 ? "0" : "" + $"{ time.Seconds}";

            track = new SpotifyTrack
            {
                Name     = obj?.artists[0]?.name.ToString() + " - " + obj?.name.ToString(),
                Id       = obj?.id.ToString(),
                Image    = obj?.album?.images[1].url.ToString(),
                Duration = $"{time.Minutes}:{second}"
            };

            return(track);
        }
Ejemplo n.º 2
0
        private async Task <bool> UpdateTrackInfoUsingWebApi()
        {
            if (this.Web?.API == null)
            {
                return(false);
            }

            // Pre-emptively waiting a little bit to let the remote Spotify server update its own information
            await Task.Delay(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false);

            var currentlyPlayingObject = await this.Web.API.GetCurrentlyPlayingTrackAsync().ConfigureAwait(false);

            if (currentlyPlayingObject?.Track == null || !currentlyPlayingObject.Track.IsValid())
            {
                return(false);
            }

            ISpotifyTrack newTrack = currentlyPlayingObject.Track;

            if (!SpotifyTrack.Equal(this.CurrentTrack, newTrack))
            {
                ISpotifyTrack oldTrack = this.CurrentTrack;
                this.CurrentTrack = newTrack;
                await this.OnTrackChanged(oldTrack).ConfigureAwait(false);
            }

            await this.OnPlayStateChanged(currentlyPlayingObject.IsPlaying).ConfigureAwait(false);

            return(true);
        }
Ejemplo n.º 3
0
 public TracksController(IMapper mapper, SpotifyTrack trackrepo,
                         ICookieManager cookiesManager, FullTrackViewModel model)
 {
     _mapper         = mapper;
     _trackrepo      = trackrepo;
     _model          = model;
     _cookiesManager = cookiesManager;
 }
Ejemplo n.º 4
0
 public static TrackListViewModel ToListViewModel(this SpotifyTrack model)
 {
     return(new TrackListViewModel {
         Name = model.Name,
         ListeningLink = model.ListeningURL,
         Artists = string.Join(" - ", model.Artists.Select(x => x.Name)),
         DanceabilityScore = CalculateScore(model.DanceabilityValue)
     });
 }
Ejemplo n.º 5
0
 private SpotifyPlayer(JObject obj) : base(obj)
 {
     //Device = obj.GetObject("device", SpotifyDevice.Parse);
     //RepeatState = obj.GetString("repeat_state");
     //ShuffleState = obj.GetString("shuffle_state");
     Context    = obj.GetObject("context", SpotifyContext.Parse);
     TimeStamp  = obj.GetInt64("timestamp");
     ProgressMs = int.Parse(obj.GetString("progress_ms"));
     IsPlaying  = bool.Parse(obj.GetString("is_playing"));
     Item       = obj.GetObject("item", SpotifyTrack.Parse);
 }
Ejemplo n.º 6
0
    void ExtractTrack(string response)
    {
        SpotifyItem item = SpotifyItem.CreateFromJSON(response);

        /* If no track is being listened */
        if (item == null)
        {
            trackName.text  = "No track selected";
            albumName.text  = "";
            artistName.text = "";
            deviceName.text = "";
        }
        else
        {
            SpotifyTrack track = item.item;


            /* Setting the current value of the progress bar */
            slider.value = item.progress_ms;

            deviceName.text = "Listening on " + item.device.name;

            if (!item.is_playing && !isPaused)
            {
                animator.SetBool("paused", true);
                isPaused = true;
            }
            else if (item.is_playing && isPaused)
            {
                animator.SetBool("paused", false);
                isPaused = false;
            }

            /* Check to see if track has changed */
            if (trackName.text != track.name)
            {
                trackName.text  = track.name;
                artistName.text = "by " + track.artists[0].name;

                /* Setting the max value of the progress bar */
                slider.maxValue = track.duration_ms;

                /* If album is a new one, download image and change image */
                if (track.album.name != albumName.text)
                {
                    albumName.text = track.album.name;

                    animator.SetBool("loading", true);

                    StartCoroutine(DownloadAlbumImage(track.album.images));
                }
            }
        }
    }
Ejemplo n.º 7
0
        private async Task <bool> TryPlaySpotifyAsync(IMusicPlayerService music, ITextChannel textChan, IGuildUser guser, string url)
        {
            SpotifyTrack track = await this.SpotifyToTrackAsync(url);

            if (track == null)
            {
                return(false);
            }

            await music.AddTrackAsync(guser.VoiceChannel, textChan, track);

            return(true);
        }
Ejemplo n.º 8
0
        private async void SpotifyWindowTitleWatcher_TitleChanged(object sender, WindowTitleChangedEventArgs e)
        {
            // TODO: Refactor this method
            try
            {
                if (logger.IsDebugEnabled)
                {
                    logger.Debug($"Spotify's window title changed: \"{e.NewTitle}\". Fetching song info...");
                }

                if (!(Settings.Current.EnableSpotifyWebApi && this.IsWebApiRunning &&
                      await this.UpdateTrackInfoUsingWebApi().ConfigureAwait(false)))
                {
                    // If the WebAPIs are disabled or they weren't able to retrieve the song info, fallback to
                    // the old method based on the title of Spotify's window.

                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug("Fetching song info using old method based on the title of Spotify's window...");
                    }

                    bool updateSong = true;
                    if (SpotifyWindow.PausedTitles.Contains(e.NewTitle, StringComparer.InvariantCulture))
                    {
                        await this.OnPlayStateChanged(false).ConfigureAwait(false);

                        updateSong = false;
                    }
                    else if (!this.IsPlaying)
                    {
                        await this.OnPlayStateChanged(true).ConfigureAwait(false);
                    }

                    if (updateSong)
                    {
                        ISpotifyTrack newSong = Song.FromSpotifyWindowTitle(e.NewTitle);
                        if (!SpotifyTrack.Equal(this.CurrentTrack, newSong))
                        {
                            ISpotifyTrack oldSong = this.CurrentTrack;
                            this.CurrentTrack = newSong;
                            await this.OnTrackChanged(oldSong).ConfigureAwait(false);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                logger.Error($"Unhandled exception in {nameof(this.SpotifyWindowTitleWatcher_TitleChanged)}.", exception);
            }
        }
Ejemplo n.º 9
0
        public SpotifyTrack GetTrack()
        {
            SpotifyTrack newTrack = new SpotifyTrack();

            if (item.id == "Unavailable")
            {
                return(newTrack);
            }

            // Unique ID
            newTrack.ID = item.id;

            // Process Artist Information
            string artist = string.Empty;

            foreach (Artist a in item.artists)
            {
                artist += a.name + ", ";
            }

            if (artist.EndsWith(", ", StringComparison.Ordinal))
            {
                artist = artist.Substring(0, artist.LastIndexOf(", ", StringComparison.Ordinal));
            }
            newTrack.Artist = artist;

            // Process Track
            newTrack.Track = item.name;

            newTrack.Album = item.album.name;

            // URL
            if (item.external_urls.ContainsKey("spotify"))
            {
                newTrack.TrackURL = item.external_urls["spotify"];
            }

            // Image
            if (item.album.images.Count > 0)
            {
                newTrack.ImageURL = item.album.images[0].url;
                foreach (Image i in item.album.images)
                {
                    newTrack.Images.Add(new SpotifyTrack.Image(i.url, i.width, i.height));
                }
            }

            return(newTrack);
        }
Ejemplo n.º 10
0
 public static Track CreateTrack(SpotifyTrack inTrack)
 {
     return(new Track
     {
         Id = inTrack.Id,
         Uri = inTrack.Uri,
         Name = inTrack.Name,
         Album = CreateAlbum(inTrack.Album),
         Type = inTrack.Type,
         Artists = CreateArtists(inTrack.Artists),
         TrackNumber = inTrack.TrackNumber,
         DiscNumber = inTrack.DiscNumber,
         Duration = TimeSpan.FromMilliseconds(inTrack.DurationMs).ToString("g")
     });
 }
Ejemplo n.º 11
0
        private async Task OnGuildMemberUpdatedAsync(SocketGuildUser before, SocketGuildUser after)
        {
            if (before.Activity == after.Activity)
            {
                return;
            }
            if (!(after.Activity is SpotifyGame activity))
            {
                return;
            }

            if (!_db.Tracks.Any(x => x.Id == activity.TrackId))
            {
                var track = new SpotifyTrack
                {
                    Id          = activity.TrackId,
                    Artists     = string.Join(", ", activity.Artists),
                    AlbumArtUrl = activity.AlbumArtUrl,
                    AlbumTitle  = activity.AlbumTitle,
                    TrackTitle  = activity.TrackTitle
                };

                if (activity.Duration.HasValue)
                {
                    track.Duration = activity.Duration.Value.Ticks;
                }

                await _db.Tracks.AddAsync(track);
            }

            await _db.Listens.AddAsync(new SpotifyListen
            {
                GuildId = after.Guild.Id,
                UserId  = after.Id,
                TrackId = activity.TrackId
            });

            await _db.SaveChangesAsync();

            _logger.LogInformation($"{after.Guild}: {activity.ToString()}");
        }
Ejemplo n.º 12
0
        public async Task AddSpotifyTrackAsync(Artist artist, string track, string url)
        {
            if (artist == null || string.IsNullOrEmpty(url) || string.IsNullOrEmpty(track))
            {
                return;
            }

            string formattedTrack = track.Length > 255
                ? track.Substring(0, 255)
                : track;

            var existingTrack = await context.SpotifyTracks.FirstOrDefaultAsync(t =>
                                                                                t.Track == formattedTrack &&
                                                                                t.Artist.Name == artist.Name);

            if (existingTrack != null)
            {
                return;
            }

            var spotifyTrack = new SpotifyTrack
            {
                Url    = url,
                Artist = artist,
                Track  = formattedTrack
            };

            await context.SpotifyTracks.AddAsync(spotifyTrack);

            try
            {
                await context.SaveChangesAsync();
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 13
0
        private static EmbedBuilder CreateTrackEmbed(SpotifyTrack track)
        {
            var embed = new EmbedBuilder
            {
                Color  = BotService.DefaultEmbedColour,
                Author = new EmbedAuthorBuilder
                {
                    Name    = track.Artists.Select(a => a.Name).Humanize(),
                    IconUrl = track.Album.Images.FirstOrDefault()?.Url,
                    Url     = track.Artists.FirstOrDefault()?.Id.Url
                },
                Title        = track.Name,
                ThumbnailUrl = track.Album.Images.FirstOrDefault()?.Url
            };

            embed.AddField("Length", $"{track.Duration.Minutes} minutes, {track.Duration.Seconds} seconds", true);
            embed.AddField("Release Date", track.Album.ReleaseDate.ToString("D"), true);
            embed.AddField("Album", UrlHelper.CreateMarkdownUrl(track.Album.Name, track.Album.Id.Url), true);
            embed.AddField("Is Explicit", track.HasExplicitLyrics ? "Yes" : "No", true);

            embed.AddField("\u200B", UrlHelper.CreateMarkdownUrl("Click to listen!", track.Id.Url));

            return(embed);
        }
Ejemplo n.º 14
0
 public SpotifyTrackViewModel(SpotifyTrack track)
 {
     _track   = track;
     _visible = true;
 }
Ejemplo n.º 15
0
        public async Task <IEnumerable <SpotifyTrack> > SearchTracks(IEnumerable <Track> tracksToFind, string accessToken)
        {
            Logger.Section($"Searching For {tracksToFind.Count()} tracks on Spotify");
            var foundTracks      = new List <SpotifyTrack>(100);
            int messageThreshold = 50;
            int counter          = 0;

            foreach (var trackToFind in tracksToFind)
            {
                var title = trackToFind.Title;


                title = title.Replace(" ", "%20");
                //  artist = artist.Replace(" ", "%20");
                var queryString = new QueryString("q", $"{title}%20").Add("type", "track").Format(false);
                var uri         = $"{TrackSearchEndpoint}?{queryString}";
                var message     = new HttpRequestMessage(HttpMethod.Get, uri);
                message.Headers.Add("Authorization", $"Bearer {accessToken}");
                var response = await _httpClient.SendAsync(message);

                var json = await response.Content.ReadAsStringAsync();

                var jobject = JObject.Parse(json);
                var items   = jobject.SelectToken("tracks.items") as JArray;
                if (items == null)
                {
                    continue;
                }
                var tracks = new List <SpotifyTrack>();
                foreach (JObject node in items)
                {
                    var type    = node.SelectToken("type");
                    var artists = node.SelectToken("artists") as JArray;
                    if (artists != null && artists.Any(x => x.SelectToken("name").Value <string>().Equals(trackToFind.Artist, StringComparison.OrdinalIgnoreCase)))
                    {
                        if (type != null)
                        {
                            if (type.Value <string>().Equals("track"))
                            {
                                var track = new SpotifyTrack
                                {
                                    AlbumId = node.SelectToken("album.id").Value <string>(),
                                    Album   = node.SelectToken("album.name").Value <string>(),
                                    Title   = node.SelectToken("name").Value <string>(),
                                    Id      = node.SelectToken("id").Value <string>(),
                                    Uri     = node.SelectToken("uri").Value <string>()
                                };
                                trackToFind.UnqiueId = node.SelectToken("uri").Value <string>();

                                if (track.Uri != null)
                                {
                                    foundTracks.Add(track);
                                    break;
                                }
                            }
                        }
                    }
                }
                counter++;
                if (counter % messageThreshold == 0)
                {
                    Logger.Magenta($"Processed {foundTracks.Count} tracks thus far....");
                }
            }
            Logger.Magenta($"Found {foundTracks.Count} tracks from spotify.");
            return(foundTracks);
        }
Ejemplo n.º 16
0
        private async void SpotifyWindowTitleWatcher_TitleChanged(object sender, WindowTitleChangedEventArgs e)
        {
            // TODO: Refactor this method
            try
            {
                if (logger.IsDebugEnabled)
                {
                    logger.Debug($"Spotify's window title changed: \"{e.NewTitle}\". Fetching song info...");
                }

                bool shouldUpdateUsingWindowTitle = !(Settings.Current.EnableSpotifyWebApi && this.IsWebApiRunning);

                this.apiTrackDelayedUpdateTimer?.Dispose();
                bool tooFast = this.songChangesInTimespan >= 3;
                if (!shouldUpdateUsingWindowTitle && tooFast)
                {
                    logger.Debug($"Songs are being changed too fast ({this.songChangesInTimespan} times in {this.songChangeBuffer.TotalMilliseconds} ms)!");
                    this.apiTrackDelayedUpdateTimer = new Timer(async state =>
                    {
                        logger.Debug($"Executing delayed track update using WebAPI (\"{state}\")");
                        await this.UpdateTrackInfoUsingWebApi().ConfigureAwait(false);
                    }, e.NewTitle, this.songChangeBuffer, TimeSpan.FromMilliseconds(-1));
                    shouldUpdateUsingWindowTitle = true;
                }

                if (!shouldUpdateUsingWindowTitle)
                {
                    shouldUpdateUsingWindowTitle = !await this.UpdateTrackInfoUsingWebApi().ConfigureAwait(false);
                }

                if (shouldUpdateUsingWindowTitle)
                {
                    // If the WebAPIs are disabled or they weren't able to retrieve the song info, fallback to
                    // the old method based on the title of Spotify's window.

                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug("Fetching song info using old method based on the title of Spotify's window...");
                    }

                    bool updateSong = true;
                    if (SpotifyWindow.PausedTitles.Contains(e.NewTitle, StringComparer.InvariantCulture))
                    {
                        await this.OnPlayStateChanged(false).ConfigureAwait(false);

                        updateSong = false;
                    }
                    else if (!this.IsPlaying)
                    {
                        await this.OnPlayStateChanged(true).ConfigureAwait(false);
                    }

                    if (updateSong)
                    {
                        ISpotifyTrack newSong = Song.FromSpotifyWindowTitle(e.NewTitle);
                        if (!SpotifyTrack.Equal(this.CurrentTrack, newSong))
                        {
                            ISpotifyTrack oldSong = this.CurrentTrack;
                            this.CurrentTrack = newSong;
                            await this.OnTrackChanged(oldSong).ConfigureAwait(false);
                        }
                    }
                }

                this.songChangesInTimespan++;
                if (DateTime.Now - this.lastSongChange > this.songChangeBuffer)
                {
                    this.songChangesInTimespan = 0;
                }
                this.lastSongChange = DateTime.Now;
            }
            catch (Exception exception)
            {
                logger.Error($"Unhandled exception in {nameof(this.SpotifyWindowTitleWatcher_TitleChanged)}.", exception);
            }
        }