Beispiel #1
0
        private async void TryLoadTopArtistBackground(LastArtist artist)
        {
            if (_backgroundLoaded)
            {
                return;
            }
            else if (artist == null)
            {
                HubBackgroundImage = HUB_BACKGROUND_DEFAULT;
                return;
            }

            _backgroundLoaded = true;

            string imagePath = await _imagesCacheService.GetCachedArtistImage(artist.Name);

            if (imagePath == null)
            {
                HubBackgroundImage = HUB_BACKGROUND_DEFAULT;
                imagePath          = await _imagesCacheService.CacheAndGetArtistImage(artist.Name);
            }

            if (imagePath != null)
            {
                HubBackgroundImage = imagePath;
            }
            else
            {
                _backgroundLoaded = false;
            }
        }
Beispiel #2
0
        private LastArtist CreateArtist(string artist, string artwork, bool withSimilar = true)
        {
            var a = new LastArtist
            {
                Name      = artist,
                MainImage = new LastImageSet {
                    ExtraLarge = new Uri(artwork)
                },
                Bio = new LastBio
                {
                    YearFormed = 2011,
                    Content    = "In the begining it was called musicDownload... then it was reborn as something else..."
                }
            };

            if (withSimilar)
            {
                a.Similar = new List <LastArtist>
                {
                    CreateArtist("Iggy Azalea",
                                 "http://musicimage.xboxlive.com/content/music.1F154700-0200-11DB-89CA-0019B92A3933/image?locale=en-US", false),
                    CreateArtist("Ariana Grande",
                                 "http://musicimage.xboxlive.com/content/music.89C84300-0200-11DB-89CA-0019B92A3933/image?locale=en-US", false),
                    CreateArtist("Jason Derulo",
                                 "http://musicimage.xboxlive.com/content/music.9C080600-0200-11DB-89CA-0019B92A3933/image?locale=en-US", false)
                };
            }

            return(a);
        }
Beispiel #3
0
        private async void LoadArtistInfo(LastArtist lastArtist)
        {
            progress.IsActive = true;

            this.DataContext = lastArtist;
            header.SetContext(lastArtist);

            var result = await LastFm.Current.Client.Artist.GetTopTracksAsync(lastArtist.Name, true, 1, 10);

            if (result.Success)
            {
                var list = result.Content.ToList();
                if (list.Count > 0)
                {
                    LoadArtistTopTracks(list);
                }
            }

            var resultALB = await LastFm.Current.Client.Artist.GetTopAlbumsAsync(lastArtist.Name, true, 1, 10);

            if (resultALB.Success)
            {
                var list = resultALB.Content.ToList();
                if (list.Count > 0)
                {
                    LoadTopAlbums(list);
                }
            }

            progress.IsActive = false;
        }
Beispiel #4
0
        private static string ScrapeImage(LastArtist artist)
        {
            var    req      = (HttpWebRequest)WebRequest.Create(artist.Url);
            var    response = (HttpWebResponse)req.GetResponse();
            string result;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return("https://lastfm-img2.akamaized.net/i/u/174s/4128a6eb29f94943c9d206c08e625904");
            }
            var receiveStream = response.GetResponseStream();

            var readStream = response.CharacterSet == null ? new StreamReader(receiveStream ?? throw new Exception()) : new StreamReader(receiveStream ?? throw new Exception(), Encoding.GetEncoding(response.CharacterSet));
            var data       = readStream.ReadToEnd();

            response.Close();
            readStream.Close();
            try
            {
                result = data.Substring(data.IndexOf("<meta property=\"og:image\"           content=\"", StringComparison.Ordinal) + 45, 150);
                result = result.Remove(result.IndexOf("\"", StringComparison.Ordinal));
            }
            catch (Exception)
            {
                result = "https://lastfm-img2.akamaized.net/i/u/174s/4128a6eb29f94943c9d206c08e625904";
            }
            return(result);
        }
        public async Task HandleResponseSingle()
        {
            var expectedArtist = new LastArtist
            {
                Name      = "Liars",
                Mbid      = "03098741-08b3-4dd7-b3f6-1b0bfa2c879c",
                Url       = new Uri("http://www.last.fm/music/Liars"),
                MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/2261874.jpg",
                                             "http://userserve-ak.last.fm/serve/64/2261874.jpg",
                                             "http://userserve-ak.last.fm/serve/126/2261874.jpg",
                                             "http://userserve-ak.last.fm/serve/252/2261874.jpg",
                                             "http://userserve-ak.last.fm/serve/_/2261874/Liars.jpg")
            };

            var file     = GetFileContents("UserApi.UserGetRecommendedArtistsSingle.json");
            var response = CreateResponseMessage(file);
            //var response = CreateResponseMessage(Encoding.UTF8.GetString(UserApiResponses.UserGetRecommendedArtistsSingle));
            var parsed = await _commmand.HandleResponse(response);

            Assert.IsTrue(parsed.Success);

            var expectedJson = expectedArtist.WrapEnumerable().TestSerialise();
            var actualJson   = parsed.Content.TestSerialise();

            Assert.AreEqual(expectedJson, actualJson, expectedJson.DifferencesTo(actualJson));
        }
Beispiel #6
0
        public async Task HandleResponseSingle()
        {
            var command = new GetArtistsCommand(MAuth.Object, "user")
            {
                Page  = 2,
                Count = 1
            };

            var expectedArtist = new LastArtist
            {
                Name      = "Crystal Castles",
                PlayCount = 4219,
                Mbid      = "b1570544-93ab-4b2b-8398-131735394202",
                Url       = new Uri("https://www.last.fm/music/Crystal+Castles"),
                MainImage = new LastImageSet(
                    "https://lastfm-img2.akamaized.net/i/u/34s/f36a92bfbd7f8b579c91942c6a428d69.png",
                    "https://lastfm-img2.akamaized.net/i/u/64s/f36a92bfbd7f8b579c91942c6a428d69.png",
                    "https://lastfm-img2.akamaized.net/i/u/174s/f36a92bfbd7f8b579c91942c6a428d69.png",
                    "https://lastfm-img2.akamaized.net/i/u/300x300/f36a92bfbd7f8b579c91942c6a428d69.png",
                    "https://lastfm-img2.akamaized.net/i/u/f36a92bfbd7f8b579c91942c6a428d69.png")
            };

            var response = CreateResponseMessage(Encoding.UTF8.GetString(LibraryApiResponses.LibraryGetArtistsSingle));
            var actual   = await command.HandleResponse(response);

            Assert.IsTrue(actual.Success);
            TestHelper.AssertSerialiseEqual(expectedArtist, actual.Content.Single()); // Testing the second track returned
        }
Beispiel #7
0
        private static MediaInfo ConvertFromLastArtist(LastArtist lastArtist)
        {
            var mediaInfo = new MediaInfo
            {
                LastFm = new Models.LastFm
                {
                    LastFmId = lastArtist.Id,
                    Url      = lastArtist.Url,
                    Details  = lastArtist.Bio?.Content,
                    Name     = lastArtist.Name
                },
                MusicBrainzId = lastArtist.Mbid,
            };

            if (lastArtist.MainImage == null)
            {
                return(mediaInfo);
            }

            mediaInfo.LastFm.SmallImageUrl   = lastArtist.MainImage.Small;
            mediaInfo.LastFm.MediumImageUrl  = lastArtist.MainImage.Medium;
            mediaInfo.LastFm.LargeImageUrl   = lastArtist.MainImage.Large;
            mediaInfo.LastFm.LargestImageUrl = lastArtist.MainImage.Largest;

            return(mediaInfo);
        }
Beispiel #8
0
 public ArtistDto MapArtist(LastArtist artist)
 {
     return(new ArtistDto {
         Name = artist.Name,
         Biography = "no bio",
         PictureURL = artist.MainImage.Mega.AbsoluteUri
     });
 }
 public static Artist ToArtist(this LastArtist lastArtist)
 {
     return(new Artist
     {
         Name = lastArtist.Name.Trim().Replace("  ", " "),
         ProviderId = lastArtist.Id
     });
 }
Beispiel #10
0
 public static Artist ToArtist(this LastArtist lastArtist)
 {
     return(new Artist
     {
         Name = lastArtist.Name,
         ProviderId =
             !string.IsNullOrEmpty(lastArtist.Mbid) ? ("mbid." + lastArtist.Mbid) : ("lastid." + lastArtist.Id),
     });
 }
Beispiel #11
0
 private WebArtist CreateArtist(LastArtist artist, bool lowest = false)
 {
     return(new WebArtist()
     {
         Name = artist.Name,
         Artwork = GetImage(artist?.MainImage, lowest),
         Id = artist.Id != null ? artist.Id : artist.Mbid,
     });
 }
Beispiel #12
0
 public static Artist ToArtist(this LastArtist lastArtist)
 {
     return(new Artist
     {
         Name = lastArtist.Name.Trim().Replace("  ", " "),
         ProviderId =
             !string.IsNullOrEmpty(lastArtist.Mbid) ? ("mbid." + lastArtist.Mbid) : ("lastid." + lastArtist.Id)
     });
 }
Beispiel #13
0
 private WebArtist CreateArtist(LastArtist artist)
 {
     return(new WebArtist(GetType())
     {
         Name = artist.Name,
         Token = artist.Name,
         Artwork = artist.MainImage?.Largest
     });
 }
Beispiel #14
0
        private async Task <LastArtist> GetFullInfoArtistFromLastFm(string artistName)
        {
            LastArtist artist = (await client.Artist.GetInfoAsync(artistName)).Content ?? new LastArtist();

            artist.Bio = artist.Bio ?? new LastWiki();
            if (artist.Bio.Content == null)
            {
                artist.Bio.Content = "no bio";
            }
            return(artist);
        }
Beispiel #15
0
        private async void lastFmButton_Click(object sender, RoutedEventArgs e)
        {
            var result = await LastFm.Current.Client.Artist.GetInfoAsync(this.ART.Name, ApplicationInfo.Current.Language, true);

            if (result.Success)
            {
                LastArtist artist = result.Content;

                PageHelper.MainPage.Navigate(typeof(ProfilePage), artist);
            }
        }
Beispiel #16
0
 private void OnGoToSimilarArtistInfoCommand(LastArtist artist)
 {
     if (_purchaseService.IsFullVersionPurchased)
     {
         _navigationService.Navigate("ArtistInfoView", JsonConvert.SerializeObject(artist, _lastImageSetConverter));
     }
     else
     {
         _navigationService.Navigate("PurchaseView", JsonConvert.SerializeObject(
                                         new KeyValuePair <string, string>("ArtistInfoView", JsonConvert.SerializeObject(artist, _lastImageSetConverter))));
     }
 }
Beispiel #17
0
 private void OnGoToArtistInfoCommand(LastArtist artist)
 {
     if (artist.Name == VKSAVER_SEE_ALSO_TEXT)
     {
         OnGoTopArtistsCommand();
     }
     else
     {
         _navigationService.Navigate("ArtistInfoView",
                                     JsonConvert.SerializeObject(artist, _lastImageSetConverter));
     }
 }
Beispiel #18
0
        private async void recentTopArtists_ItemClick(object sender, ItemClickEventArgs e)
        {
            LastArtist la = e.ClickedItem as LastArtist;

            var result = await LastFm.Current.Client.Artist.GetInfoAsync(la.Name, ApplicationInfo.Current.Language, true);

            if (result.Success)
            {
                LastArtist artist = result.Content;
                //artist.PlayCount = la.PlayCount;
                PageHelper.MainPage.Navigate(typeof(ProfilePage), artist);
            }
        }
        /// <summary>
        /// Creates generic artists.
        /// Only the name is set to "TestArtist" + ID.
        /// </summary>
        /// <param name="amount">Amount of artists to create.</param>
        /// <returns>Newly created artists.</returns>
        public static LastArtist[] CreateGenericArtists(int amount)
        {
            LastArtist[] artists = new LastArtist[amount];
            for (int i = 0; i < artists.Length; i++)
            {
                artists[i] = new LastArtist()
                {
                    Name = $"TestArtist{i}"
                };
            }

            return(artists);
        }
Beispiel #20
0
        private async void listView_ItemClick(object sender, ItemClickEventArgs e)
        {
            LastArtist artist = e.ClickedItem as LastArtist;

            var result = await LastFm.Current.Client.Artist.GetInfoAsync(artist.Name, ApplicationInfo.Current.Language, true);

            if (result.Success)
            {
                LastArtist a = result.Content;

                PageHelper.MainPage.Navigate(typeof(ProfilePage), a);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Creates generic artists.
        /// Only the name is set to "TestArtist" + ID.
        /// </summary>
        /// <param name="amount">Amount of artists to create.</param>
        /// <returns>Newly created artists.</returns>
        public static LastArtist[] CreateGenericArtists(int amount)
        {
            LastArtist[] artists = new LastArtist[amount];
            for (int i = 0; i < artists.Length; i++)
            {
                artists[i] = new LastArtist()
                {
                    Name = string.Format("TestArtist{0}", i)
                };
            }

            return(artists);
        }
Beispiel #22
0
 /// <summary>
 /// Creates the text for the <see cref="CollageType.Artists"/>.
 /// </summary>
 /// <param name="a">Downloaded artist info.</param>
 /// <returns>String with info text.</returns>
 private string CreateArtistText(LastArtist a)
 {
     if (ShowNames && ShowPlaycounts)
     {
         return($"{a.Name}{Environment.NewLine}Plays: {a.PlayCount}");
     }
     else if (ShowNames)
     {
         return(a.Name);
     }
     else if (ShowPlaycounts)
     {
         return($"Plays: {a.PlayCount}");
     }
     else
     {
         return(string.Empty);
     }
 }
Beispiel #23
0
 /// <summary>
 /// Creates the text for the <see cref="CollageType.Artists"/>.
 /// </summary>
 /// <param name="a">Downloaded artist info.</param>
 /// <returns>String with info text.</returns>
 private string CreateArtistText(LastArtist a)
 {
     if (ShowNames && ShowPlaycounts)
     {
         return(string.Format("{0}{1}Plays: {2}", a.Name, Environment.NewLine, a.PlayCount));
     }
     else if (ShowNames)
     {
         return(string.Format("{0}", a.Name));
     }
     else if (ShowPlaycounts)
     {
         return(string.Format("Plays: {0}", a.PlayCount));
     }
     else
     {
         return(string.Empty);
     }
 }
        public async Task HandleResponseSingle()
        {
            var command = new GetTopArtistsCommand(MAuth.Object, USER, SPAN)
            {
                Page  = 1,
                Count = 1
            };

            command.SetParameters();

            var expectedArtist = new LastArtist
            {
                Name      = "Anathema",
                PlayCount = 5216,
                Mbid      = "20aa23e3-3532-42ca-acf6-e8c2e9df2688",
                Url       = new Uri("http://www.last.fm/music/Anathema"),
                MainImage =
                    new LastImageSet("http://userserve-ak.last.fm/serve/34/12571597.jpg",
                                     "http://userserve-ak.last.fm/serve/64/12571597.jpg",
                                     "http://userserve-ak.last.fm/serve/126/12571597.jpg",
                                     "http://userserve-ak.last.fm/serve/252/12571597.jpg",
                                     "http://userserve-ak.last.fm/serve/_/12571597/Anathema+Judgement+promo.jpg")
            };

            var file     = GetFileContents("UserApi.UserGetTopArtistsSingle.json");
            var response = CreateResponseMessage(file);
            //var response = CreateResponseMessage(Encoding.UTF8.GetString(UserApiResponses.UserGetTopArtistsSingle));
            var parsed = await command.HandleResponse(response);

            Assert.IsTrue(parsed.Success);
            Assert.AreEqual(1, parsed.Page);
            Assert.AreEqual(1, parsed.PageSize);
            Assert.AreEqual(1124, parsed.TotalItems);
            Assert.AreEqual(1124, parsed.TotalPages);
            Assert.AreEqual(1, parsed.Content.Count);

            var actualArtist = parsed.Content.First();

            TestHelper.AssertSerialiseEqual(expectedArtist, actualArtist);
        }
Beispiel #25
0
        public async void SetContext(LastArtist artist)
        {
            this.DataContext = LastART = artist;

            audictiveButton.Visibility = Ctr_Artist.Current.ArtistExists(new Artist()
            {
                Name = artist.Name
            }) ? Visibility.Visible : Visibility.Collapsed;

            buttonsArea.Visibility = Visibility.Collapsed;

            BitmapImage b = new BitmapImage();

            rootBrush.ImageSource = b;
            b.UriSource           = LastART.MainImage.Large;

            ellipse.SetSource(LastART.MainImage.Large, CircleImage.ImageType.LastFmArtist);

            title.Text = LastART.Name.ToUpper();
            //subtitle1.Text = Convert.ToString(LastART.PlayCount);
            var tags = LastART.Tags.ToList();

            lastFmTagsList.ItemsSource = tags;

            // FORMAT THE LISTENERS COUNT TO DISPLAY AS A GROUPED INT (1,000,000)
            DecimalFormatter formatter = new DecimalFormatter()
            {
                IsGrouped      = true,
                FractionDigits = 0
            };

            try
            {
                playCount.Text = formatter.FormatInt(LastART.Stats.Listeners) + " " + ApplicationInfo.Current.Resources.GetString("Listeners").ToUpper();
            }
            catch
            {
            }
        }
Beispiel #26
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="artist">Artist to pull info from.</param>
 public Artist(LastArtist artist)
     : this(artist.Name, artist.Mbid, artist.MainImage?.Large)
 {
 }
Beispiel #27
0
        public async Task HandleSuccessResponse()
        {
            var expectedArtist = new LastArtist()
            {
                Name      = "Frightened Rabbit",
                Mbid      = "dc21d171-7204-4759-9fd0-77d031aeb40c",
                Url       = new Uri("http://www.last.fm/music/Frightened+Rabbit"),
                MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/50340089.jpg",
                                             "http://userserve-ak.last.fm/serve/64/50340089.jpg",
                                             "http://userserve-ak.last.fm/serve/126/50340089.jpg",
                                             "http://userserve-ak.last.fm/serve/252/50340089.jpg",
                                             "http://userserve-ak.last.fm/serve/_/50340089/Frightened+Rabbit+frabbit.jpg"),
                // todo streamable
                OnTour  = false,
                Similar = new List <LastArtist>
                {
                    new LastArtist
                    {
                        Name      = "Admiral Fallow",
                        Url       = new Uri("http://www.last.fm/music/Admiral+Fallow"),
                        MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/48454975.jpg",
                                                     "http://userserve-ak.last.fm/serve/64/48454975.jpg",
                                                     "http://userserve-ak.last.fm/serve/126/48454975.jpg",
                                                     "http://userserve-ak.last.fm/serve/252/48454975.jpg",
                                                     "http://userserve-ak.last.fm/serve/500/48454975/Admiral+Fallow+l_1185fb2755064ccfbab2871ecec8.jpg")
                    },
                    new LastArtist
                    {
                        Name      = "The Twilight Sad",
                        Url       = new Uri("http://www.last.fm/music/The+Twilight+Sad"),
                        MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/18201771.jpg",
                                                     "http://userserve-ak.last.fm/serve/64/18201771.jpg",
                                                     "http://userserve-ak.last.fm/serve/126/18201771.jpg",
                                                     "http://userserve-ak.last.fm/serve/252/18201771.jpg",
                                                     "http://userserve-ak.last.fm/serve/500/18201771/The+Twilight+Sad+hi+how+are+you.jpg"),
                    },
                    new LastArtist
                    {
                        Name      = "Owl John",
                        Url       = new Uri("http://www.last.fm/music/Owl+John"),
                        MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/101981791.png",
                                                     "http://userserve-ak.last.fm/serve/64/101981791.png",
                                                     "http://userserve-ak.last.fm/serve/126/101981791.png",
                                                     "http://userserve-ak.last.fm/serve/252/101981791.png",
                                                     "http://userserve-ak.last.fm/serve/500/101981791/Owl+John+owl.png"),
                    },
                    new LastArtist
                    {
                        Name      = "We Were Promised Jetpacks",
                        Url       = new Uri("http://www.last.fm/music/We+Were+Promised+Jetpacks"),
                        MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/53527397.jpg",
                                                     "http://userserve-ak.last.fm/serve/64/53527397.jpg",
                                                     "http://userserve-ak.last.fm/serve/126/53527397.jpg",
                                                     "http://userserve-ak.last.fm/serve/252/53527397.jpg",
                                                     "http://userserve-ak.last.fm/serve/_/53527397/We+Were+Promised+Jetpacks+wwpj.jpg"),
                    },
                    new LastArtist
                    {
                        Name      = "Meursault",
                        Url       = new Uri("http://www.last.fm/music/Meursault"),
                        MainImage = new LastImageSet("http://userserve-ak.last.fm/serve/34/41921789.jpg",
                                                     "http://userserve-ak.last.fm/serve/64/41921789.jpg",
                                                     "http://userserve-ak.last.fm/serve/126/41921789.jpg",
                                                     "http://userserve-ak.last.fm/serve/252/41921789.jpg",
                                                     "http://userserve-ak.last.fm/serve/_/41921789/Meursault+lovely+fuckwits.jpg"),
                    }
                },
                Tags = new List <LastTag>
                {
                    new LastTag("indie", "http://www.last.fm/tag/indie"),
                    new LastTag("scottish", "http://www.last.fm/tag/scottish"),
                    new LastTag("indie rock", "http://www.last.fm/tag/indie%20rock"),
                    new LastTag("folk", "http://www.last.fm/tag/folk"),
                    new LastTag("folk rock", "http://www.last.fm/tag/folk%20rock"),
                },
                Bio = new LastWiki
                {
                    Content    = "Frightened Rabbit are an <a href=\"http://www.last.fm/tag/indie%20rock\" class=\"bbcode_tag\" rel=\"tag\">indie rock</a> band which formed in 2003 in Glasgow, Scotland. The band currently consists of Scott Hutchison (vocals, guitar), Billy Kennedy (guitar, keyboards), Grant Hutchison (drums, vocals), Andy Monaghan (guitar, keyboards) and Gordon Skene (guitar, keyboards). The band has released four albums: &quot;Sing the Greys&quot; (2006), &quot;The Midnight Organ Fight&quot; (2008), &quot;The Winter of Mixed Drinks&quot; (2010) and &quot;Pedestrian Verse&quot; (2013).  \n\n        <a href=\"http://www.last.fm/music/Frightened+Rabbit\">Read more about Frightened Rabbit on Last.fm</a>.\n    \n    \nUser-contributed text is available under the Creative Commons By-SA License and may also be available under the GNU FDL.",
                    Summary    = "Frightened Rabbit are an <a href=\"http://www.last.fm/tag/indie%20rock\" class=\"bbcode_tag\" rel=\"tag\">indie rock</a> band which formed in 2003 in Glasgow, Scotland. The band currently consists of Scott Hutchison (vocals, guitar), Billy Kennedy (guitar, keyboards), Grant Hutchison (drums, vocals), Andy Monaghan (guitar, keyboards) and Gordon Skene (guitar, keyboards). The band has released four albums: &quot;Sing the Greys&quot; (2006), &quot;The Midnight Organ Fight&quot; (2008), &quot;The Winter of Mixed Drinks&quot; (2010) and &quot;Pedestrian Verse&quot; (2013).  \n\n        <a href=\"http://www.last.fm/music/Frightened+Rabbit\">Read more about Frightened Rabbit on Last.fm</a>.",
                    Published  = new DateTimeOffset(2013, 2, 6, 0, 4, 40, TimeSpan.Zero),
                    YearFormed = 2003
                },
                Stats = new LastStats
                {
                    Listeners = 513447,
                    Plays     = 0
                }
            };

            var file     = GetFileContents("ArtistApi.ArtistGetInfoSuccess.json");
            var response = CreateResponseMessage(file);
            //var response = CreateResponseMessage(Encoding.UTF8.GetString(ArtistApiResponses.ArtistGetInfoSucess));
            var parsed = await _command.HandleResponse(response);

            Assert.IsTrue(parsed.Success);

            var expectedJson = expectedArtist.TestSerialise();
            var actualJson   = parsed.Content.TestSerialise();

            Assert.AreEqual(expectedJson, actualJson, expectedJson.DifferencesTo(actualJson));
        }
Beispiel #28
0
        public async Task fmArtistsAsync(string time = "weekly", int num = 6, string user = null)
        {
            User userSettings = await _userService.GetUserSettingsAsync(Context.User);

            if (userSettings?.UserNameLastFM == null)
            {
                await UsernameNotSetErrorResponseAsync();

                return;
            }
            if (time == "help")
            {
                await ReplyAsync(
                    "Usage: `.fmartists 'weekly/monthly/yearly/alltime' 'number of artists (max 10)'` \n" +
                    "You can set your default user and your display mode through the `.fmset 'username' 'embedfull/embedmini/textfull/textmini'` command.");

                return;
            }

            if (!Enum.TryParse(time, ignoreCase: true, out ChartTimePeriod timePeriod))
            {
                await ReplyAsync("Invalid time period. Please use 'weekly', 'monthly', 'yearly', or 'alltime'.");

                return;
            }

            if (num > 10)
            {
                num = 10;
            }

            LastStatsTimeSpan timeSpan = _lastFmService.GetLastStatsTimeSpan(timePeriod);

            try
            {
                string lastFMUserName = userSettings.UserNameLastFM;

                if (user != null)
                {
                    if (await _lastFmService.LastFMUserExistsAsync(user))
                    {
                        lastFMUserName = user;
                    }
                    else if (!_guildService.CheckIfDM(Context))
                    {
                        IGuildUser guildUser = await _guildService.FindUserFromGuildAsync(Context, user);

                        if (guildUser != null)
                        {
                            User guildUserLastFM = await _userService.GetUserSettingsAsync(guildUser);

                            if (guildUserLastFM?.UserNameLastFM != null)
                            {
                                lastFMUserName = guildUserLastFM.UserNameLastFM;
                            }
                        }
                    }
                }

                PageResponse <LastArtist> artists = await _lastFmService.GetTopArtistsAsync(lastFMUserName, timeSpan, num);

                if (artists?.Any() != true)
                {
                    await ReplyAsync("No artists found on this profile. (" + lastFMUserName + ")");

                    return;
                }

                EmbedAuthorBuilder eab = new EmbedAuthorBuilder
                {
                    IconUrl = Context.User.GetAvatarUrl(),
                    Name    = userSettings.UserNameLastFM
                };

                EmbedBuilder builder = new EmbedBuilder
                {
                    Color = new Discord.Color(186, 0, 0),
                };

                builder.WithUrl("https://www.last.fm/user/" + lastFMUserName + "/library/artists");
                builder.Title = lastFMUserName + " top " + num + " artists (" + timePeriod + ")";

                const string nulltext = "[undefined]";
                int          indexval = (num - 1);
                for (int i = 0; i <= indexval; i++)
                {
                    LastArtist artist = artists.Content[i];

                    string artistName = string.IsNullOrWhiteSpace(artist.Name) ? nulltext : artist.Name;

                    int correctnum = (i + 1);
                    builder.AddField("#" + correctnum + ": " + artist.Name, artist.PlayCount.Value.ToString("N0") + " times scrobbled");
                }

                EmbedFooterBuilder embedFooter = new EmbedFooterBuilder();

                LastResponse <LastUser> userinfo = await _lastFmService.GetUserInfoAsync(lastFMUserName);

                embedFooter.Text = lastFMUserName + "'s total scrobbles: " + userinfo.Content.Playcount.ToString("N0");

                builder.WithFooter(embedFooter);

                await Context.Channel.SendMessageAsync("", false, builder.Build());

                this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, Context.Message.Content, Context.User.Username, Context.Guild?.Name, Context.Guild?.Id);
                await ReplyAsync("Unable to show Last.FM info due to an internal error.");
            }
        }
Beispiel #29
0
 private void OnGoToArtistInfoCommand(LastArtist artist)
 {
     _navigationService.Navigate("ArtistInfoView", JsonConvert.SerializeObject(artist, _lastImageSetConverter));
 }
Beispiel #30
0
        public async Task GenerateChartAsync(FMBotChart chart)
        {
            try
            {
                LastStatsTimeSpan timespan = LastStatsTimeSpan.Week;

                const string nulltext = "[undefined]";

                if (!Directory.Exists(GlobalVars.CacheFolder))
                {
                    Directory.CreateDirectory(GlobalVars.CacheFolder);
                }

                // Album mode
                if (chart.mode == 0)
                {
                    for (int albumIndex = 0; albumIndex < chart.albums.Count(); ++albumIndex)
                    {
                        LastAlbum track = chart.albums.Content[albumIndex];

                        string ArtistName = string.IsNullOrWhiteSpace(track.ArtistName) ? nulltext : track.ArtistName;
                        string AlbumName  = string.IsNullOrWhiteSpace(track.Name) ? nulltext : track.Name;

                        LastImageSet albumImages = await GetAlbumImagesAsync(ArtistName, AlbumName).ConfigureAwait(false);

                        Bitmap cover;

                        if (albumImages?.Large != null)
                        {
                            string url  = albumImages.Large.AbsoluteUri;
                            string path = Path.GetFileName(url);

                            if (File.Exists(GlobalVars.CacheFolder + path))
                            {
                                cover = new Bitmap(GlobalVars.CacheFolder + path);
                            }
                            else
                            {
                                WebRequest request = WebRequest.Create(url);
                                using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
                                {
                                    using (Stream responseStream = response.GetResponseStream())
                                    {
                                        Bitmap bitmap = new Bitmap(responseStream);

                                        cover = bitmap;
                                        using (MemoryStream memory = new MemoryStream())
                                        {
                                            using (FileStream fs = new FileStream(GlobalVars.CacheFolder + path, FileMode.Create, FileAccess.ReadWrite))
                                            {
                                                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                                                byte[] bytes = memory.ToArray();
                                                fs.Write(bytes, 0, bytes.Length);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            cover = new Bitmap(GlobalVars.ImageFolder + "unknown.png");
                        }

                        if (chart.titles)
                        {
                            Graphics text = Graphics.FromImage(cover);
                            text.DrawColorString(cover, ArtistName, new Font("Arial", 8.0f, FontStyle.Bold), new PointF(2.0f, 2.0f));
                            text.DrawColorString(cover, AlbumName, new Font("Arial", 8.0f, FontStyle.Bold), new PointF(2.0f, 12.0f));
                        }

                        chart.images.Add(cover);
                    }
                }
                // Artist mode
                else if (chart.mode == 1)
                {
                    PageResponse <LastArtist> artists = await GetTopArtistsAsync(chart.LastFMName, timespan, chart.max).ConfigureAwait(false);

                    for (int al = 0; al < chart.max; ++al)
                    {
                        LastArtist artist = artists.Content[al];

                        string ArtistName = string.IsNullOrWhiteSpace(artist.Name) ? nulltext : artist.Name;

                        LastImageSet artistImage = await GetArtistImageAsync(ArtistName).ConfigureAwait(false);

                        Bitmap cover;

                        if (artistImage?.Large != null)
                        {
                            string url  = artistImage.Large.AbsoluteUri;
                            string path = Path.GetFileName(url);

                            if (File.Exists(GlobalVars.CacheFolder + path))
                            {
                                cover = new Bitmap(GlobalVars.CacheFolder + path);
                            }
                            else
                            {
                                WebRequest request = WebRequest.Create(url);
                                using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
                                {
                                    using (Stream responseStream = response.GetResponseStream())
                                    {
                                        Bitmap bitmap = new Bitmap(responseStream);

                                        cover = bitmap;
                                        using (MemoryStream memory = new MemoryStream())
                                        {
                                            using (FileStream fs = new FileStream(GlobalVars.CacheFolder + path, FileMode.Create, FileAccess.ReadWrite))
                                            {
                                                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                                                byte[] bytes = memory.ToArray();
                                                fs.Write(bytes, 0, bytes.Length);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            cover = new Bitmap(GlobalVars.ImageFolder + "unknown.png");
                        }

                        if (chart.titles)
                        {
                            Graphics text = Graphics.FromImage(cover);
                            text.DrawColorString(cover, ArtistName, new Font("Arial", 8.0f, FontStyle.Bold), new PointF(2.0f, 2.0f));
                        }

                        chart.images.Add(cover);
                    }
                }
            }
            catch (Exception e)
            {
                //_logger.LogException("GenerateChartAsync", e);
            }
            finally
            {
                List <List <Bitmap> > ImageLists = GlobalVars.splitBitmapList(chart.images, chart.rows);

                List <Bitmap> BitmapList = new List <Bitmap>();

                foreach (List <Bitmap> list in ImageLists.ToArray())
                {
                    //combine them into one image
                    Bitmap stitchedRow = GlobalVars.Combine(list);
                    BitmapList.Add(stitchedRow);
                }

                lock (GlobalVars.charts.SyncRoot)
                {
                    GlobalVars.charts[GlobalVars.GetChartFileName(chart.DiscordUser.Id)] = GlobalVars.Combine(BitmapList, true);
                }

                foreach (Bitmap image in BitmapList.ToArray())
                {
                    image.Dispose();
                }
            }
        }