Example #1
0
        private async Task <byte[]> DownloadArtistPictureFromLastFm(string artistName)
        {
            var lastFmClient = new LastFmClient();
            var lastFmArtist = await lastFmClient.GetArtistInfo(artistName);

            if (lastFmArtist == null)
            {
                return(null);
            }
            try
            {
                var clientPic    = new HttpClient();
                var imageElement = lastFmArtist.Images.LastOrDefault(node => !string.IsNullOrEmpty(node.Url));
                if (imageElement == null)
                {
                    return(null);
                }
                HttpResponseMessage responsePic = await clientPic.GetAsync(imageElement.Url);

                byte[] img = await responsePic.Content.ReadAsByteArrayAsync();

                return(img);
            }
            catch (Exception)
            {
                Debug.WriteLine("Error getting or saving art from LastFm.");
                return(null);
            }
        }
Example #2
0
        private async Task <byte[]> DownloadAlbumPictureFromLastFm(string albumName, string albumArtist)
        {
            var lastFmClient = new LastFmClient();
            var lastFmAlbum  = await lastFmClient.GetAlbumInfo(albumName, albumArtist);

            if (lastFmAlbum == null)
            {
                return(null);
            }
            if (lastFmAlbum.Images == null || lastFmAlbum.Images.Count == 0)
            {
                return(null);
            }
            try
            {
                if (string.IsNullOrEmpty(lastFmAlbum.Images.LastOrDefault().Url))
                {
                    return(null);
                }
                var clientPic = new HttpClient();
                var url       = lastFmAlbum.Images.Count == 1 ? lastFmAlbum.Images[0].Url : lastFmAlbum.Images[lastFmAlbum.Images.Count - 2].Url;
                HttpResponseMessage responsePic = await clientPic.GetAsync(url);

                byte[] img = await responsePic.Content.ReadAsByteArrayAsync();

                return(img);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Error getting or saving art from lastFm. {0}", ex));
            }
            return(null);
        }
Example #3
0
 public void AuthGetTokenTest1()
 {
     LastFmClient target = new LastFmClient(api_key, api_secret);
     AuthGetToken actual;
     actual = target.AuthGetToken();
     Assert.IsNotNull(actual);
     Assert.IsNotNull(actual.Token);
 }
Example #4
0
        public async Task LastFmTracks(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"], (IGuildUser)command.Author);

                var period = command["Period"].HasValue ? ParseStatsPeriod(command["Period"]) : LastFmDataPeriod.Overall;
                var client = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);

                const int NumDisplayed  = 100;
                var       playcountTask = client.GetTotalPlaycount(period);
                var       results       = (await client.GetTrackScores(period, NumDisplayed, playcountTask)).ToList();
                if (!results.Any())
                {
                    throw new AbortException(GetNoScrobblesTimePeriodMessage((await command["User"].AsGuildUserOrName)?.Item2));
                }

                var pages = new PageCollectionBuilder();
                var place = 1;
                foreach (var entry in results.Take(NumDisplayed))
                {
                    pages.AppendLine($"`#{place++}` **{FormatTrackLink(entry.Entity, true)}** by **{FormatArtistLink(entry.Entity.Artist, true)}**_ – {FormatPercent(entry.Score)} ({entry.Entity.Playcount} plays)_");
                }

                var playsTotal   = await playcountTask;
                var embedFactory = new Func <EmbedBuilder>(() =>
                {
                    var author = new EmbedAuthorBuilder()
                                 .WithIconUrl(_websiteWalker.LfIconUrl)
                                 .WithName($"{user}'s top tracks {FormatStatsPeriod(period)}");

                    if (!settings.Anonymous)
                    {
                        author.WithUrl($"https://www.last.fm/user/{settings.LastFmUsername}");
                    }

                    return(new EmbedBuilder()
                           .WithColor(0xd9, 0x23, 0x23)
                           .WithAuthor(author)
                           .WithFooter($"{playsTotal} plays in total"));
                });

                await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                ThrowUserNotFound((await command["User"].AsGuildUserOrName)?.Item2);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }
Example #5
0
        public App()
        {
            UnhandledException += Application_UnhandledException;

            InitializeComponent();

            InitializePhoneApplication();

            LFMClient = new LastFmClient();
        }
Example #6
0
 public void AuthGetSessionTest1()
 {
     LastFmClient target = new LastFmClient(api_key, api_secret);
     AuthGetSession actual;
     var p = Process.Start(target.GetAuthUrl());
     Debugger.Break();
     actual = target.AuthGetSession();
     Assert.AreEqual<String>(actual.UserName, "lonelyass");
     Assert.IsFalse(String.IsNullOrWhiteSpace(actual.SessionKey));
 }
Example #7
0
        public void TrackScrobbleTest1()
        {
            LastFmClient target = new LastFmClient(api_key, api_secret, session_key);
            DateTime
                t1 = DateTime.Now.Subtract(TimeSpan.FromMinutes(15)),
                t2 = DateTime.Now.Subtract(TimeSpan.FromMinutes(10)),
                t3 = DateTime.Now.Subtract(TimeSpan.FromMinutes(3));

            IEnumerable<ScrobbleRequest> tracksToScrobble = new List<ScrobbleRequest>()
            {
                new ScrobbleRequest("Черная луна", "Агата Кристи", t1),
                new ScrobbleRequest("Секрет", "Агата Кристи", t2),
                new ScrobbleRequest("c**k-fight", "uSSSy", t3),
            };
            TrackScrobble expected = new TrackScrobble()
            {
                Accepted = 3,
                Ignored = 0,
                Scrobbles = new Scrobble[]
                {
                    new Scrobble()
                    {
                        Artist = new CorrectedString("Агата Кристи", 0),
                        Track = new CorrectedString("Черная луна", 0),
                        Timestamp = Convert.ToUInt64(UnixTime.ConvertToUTCUnixTimestamp(t1)),
                        Album = new CorrectedString(),
                        AlbumArtist = new CorrectedString(),
                        IgnoredMessage = new MessageWithCode(),
                    },
                    new Scrobble()
                    {
                        Artist = new CorrectedString("Агата Кристи", 0),
                        Track = new CorrectedString("Секрет", 0),
                        Timestamp = Convert.ToUInt64(UnixTime.ConvertToUTCUnixTimestamp(t2)),
                        Album = new CorrectedString(),
                        AlbumArtist = new CorrectedString(),
                        IgnoredMessage = new MessageWithCode(),
                    },
                    new Scrobble()
                    {
                        Artist = new CorrectedString("uSSSy", 0),
                        Track = new CorrectedString("c**k fight", 1),
                        Timestamp = Convert.ToUInt64(UnixTime.ConvertToUTCUnixTimestamp(t3)),
                        Album = new CorrectedString(),
                        AlbumArtist = new CorrectedString(),
                        IgnoredMessage = new MessageWithCode(),
                    },
                }
            };
            TrackScrobble actual;
            actual = target.TrackScrobble(tracksToScrobble);
            Assert.IsTrue(ReflectionEqualityComparer.Default.Equals(expected, actual));
        }
Example #8
0
        private void initializeScrobbler()
        {
            StartTimer();
            //StartMarqueeProgressBar();

            client      = new LastFmClient();
            client.User = new LastFmUser();

            client.User.Username = userLogin;
            client.User.Password = userPassword;

            LastFmLib.WebRequests.Handshake handshake = client.Login();

            if (handshake.succeeded)
            {
                sm            = client.GetScrobblerManager();
                scrobblerInit = true;

                if (ok.InvokeRequired)
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        ok.Text = "Confirmed!";
                        optionsPopup.Show(new Point(this.Size.Width + this.Location.X, this.Location.Y + this.Size.Height / 3));
                    });
                }
                else
                {
                    ok.Text = "Cofirmed!";
                }
            }
            else
            {
                if (ok.InvokeRequired)
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        ok.Text    = "Failed!\n (" + handshake.errorMessage + ")";
                        ok.Size    = new Size(ok.Size.Width, ok.Size.Height * 2);
                        panel.Size = new Size(panel.Width, panel.Height + ok.Size.Height / 2);
                        optionsPopup.Show(new Point(this.Size.Width + this.Location.X, this.Location.Y + this.Size.Height / 3));
                    });
                }
                else
                {
                    ok.Text = "Failed!";
                }
            }

            StopTimer();
            StopMarqueeProgressBar();
        }
Example #9
0
        private async Task <List <Show> > DownloadArtistEventFromLastFm(string artistName)
        {
            var lastFmClient       = new LastFmClient();
            var lastfmArtistEvents = await lastFmClient.GetArtistEventInfo(artistName);

            if (lastfmArtistEvents == null)
            {
                return(null);
            }
            try
            {
                var shows = new List <Show>();
                foreach (var show in lastfmArtistEvents.Shows)
                {
                    DateTime date;
                    Show     Show     = null;
                    bool     tryParse = DateTime.TryParse(show.StartDate, out date);
                    if (tryParse)
                    {
                        if (show.Venue.Location.GeoPoint != null && show.Venue.Location.GeoPoint.Latitude != null &&
                            show.Venue.Location.GeoPoint.Longitute != null)
                        {
                            Show = new Show(show.Title, date, show.Venue.Location.City, show.Venue.Location.Country, show.Venue.Location.GeoPoint.Latitude, show.Venue.Location.GeoPoint.Longitute);
                        }
                        else
                        {
                            Show = new Show(show.Title, date, show.Venue.Location.City, show.Venue.Location.Country);
                        }
                    }
                    else
                    {
                        continue;
                    }
                    foreach (var artistShow in show.Artists.Artists)
                    {
                        // dirty hack
                        if (artistShow is JValue)
                        {
                            Show.Artists.Add(artistShow.Value);
                        }
                    }
                    shows.Add(Show);
                }
                return(shows);
            }
            catch (Exception exception)
            {
                Debug.WriteLine("Error when trying to map from Events collection to Artist object for artist : " + artistName + " exceptio log " + exception.ToString());
            }
            return(null);
        }
Example #10
0
        public async Task <List <Artist> > GetTopArtistGenre(string genre)
        {
            try
            {
                if (string.IsNullOrEmpty(genre))
                {
                    return(null);
                }
                var lastFmClient = new LastFmClient();
                var artists      = await lastFmClient.GetTopArtistsGenre(genre);

                return(artists);
            }
            catch
            {
            }
            return(null);
        }
Example #11
0
        protected void ChangeStatus(object o)
        {
            var lastFmClient = new LastFmClient("http://ws.audioscrobbler.com");
            while (true)
            {
                try
                {
                    Track currentTrack = lastFmClient.GetCurrentTrack("Etienne_Fab4");
                    Console.WriteLine(currentTrack);
                    ObjectFactory.GetInstance<XMPPClient>().SetStatus(currentTrack.ToString());

                }
                catch (NoTrackPlayedException)
                {
                    Console.WriteLine("no track played");
                }
            }
        }
Example #12
0
        public async Task <List <Artist> > GetArtistSimilarsArtist(string artistName)
        {
            try
            {
                if (string.IsNullOrEmpty(artistName))
                {
                    return(null);
                }
                var lastFmClient   = new LastFmClient();
                var similarArtists = await lastFmClient.GetSimilarArtists(artistName);

                return(similarArtists);
            }
            catch
            {
                Debug.WriteLine("Error getting similar artists from this artist.");
            }
            return(null);
        }
Example #13
0
        public async Task <List <Album> > GetArtistTopAlbums(string artistName)
        {
            try
            {
                if (string.IsNullOrEmpty(artistName))
                {
                    return(null);
                }
                Debug.WriteLine("Getting TopAlbums from LastFM API");
                var lastFmClient = new LastFmClient();
                var albums       = await lastFmClient.GetArtistTopAlbums(artistName);

                Debug.WriteLine("Receive TopAlbums from LastFM API");
                return(albums);
            }
            catch
            {
                Debug.WriteLine("Error getting top albums from artist.");
            }
            return(null);
        }
Example #14
0
        public async Task <string> GetArtistBiography(string artistName)
        {
            if (string.IsNullOrEmpty(artistName))
            {
                return(null);
            }
            var biography = string.Empty;

            try
            {
                var lastFmClient      = new LastFmClient();
                var artistInformation = await lastFmClient.GetArtistInfo(artistName);

                biography = artistInformation != null ? artistInformation.Biography : String.Empty;
            }
            catch
            {
                Debug.WriteLine("Failed to get artist biography from LastFM. Returning nothing.");
            }
            return(biography);
        }
Example #15
0
        public async Task NowPlayingSpotify(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"], (IGuildUser)command.Author);

                var lfm            = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);
                var nowPlayingTask = lfm.GetRecentTracks(count: 1);

                var spotify = await SpotifyClient.Create(_integrationOptions.Value.SpotifyId, _integrationOptions.Value.SpotifyKey);

                var nowPlaying = (await nowPlayingTask).FirstOrDefault();
                if (nowPlaying == null)
                {
                    await command.Reply(GetNoScrobblesMessage((await command["User"].AsGuildUserOrName)?.Item2));

                    return;
                }

                var url = await spotify.SearchTrackUrl($"{nowPlaying.Name} artist:{nowPlaying.Artist.Name}");

                if (string.IsNullOrEmpty(url))
                {
                    await command.Reply($"Can't find this track on Spotify...");

                    return;
                }

                await command.Reply($"<:sf:621852106235707392> **{user} is now listening to...**\n" + url);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }
Example #16
0
        private async Task <byte[]> DownloadArtistPictureFromLastFm(string artistName)
        {
            var lastFmClient = new LastFmClient();
            var lastFmArtist = await lastFmClient.GetArtistInfo(artistName);

            if (lastFmArtist == null)
            {
                return(null);
            }
            try
            {
                var clientPic    = new HttpClient();
                var nonEmptyImgs = lastFmArtist.Images.Where(node => !string.IsNullOrEmpty(node.Url)).ToList();
                var index        = nonEmptyImgs.Count - 1;
                if (nonEmptyImgs.Count == 6)
                {
                    index -= 1;
                }
                if (index == -1)
                {
                    return(null);
                }
                var imageElement = nonEmptyImgs.ElementAt(index);
                if (imageElement == null)
                {
                    return(null);
                }
                HttpResponseMessage responsePic = await clientPic.GetAsync(imageElement.Url);

                byte[] img = await responsePic.Content.ReadAsByteArrayAsync();

                return(img);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error getting or saving art from LastFm.");
                return(null);
            }
        }
Example #17
0
 public void TrackUpdateNowPlayingTest2()
 {
     LastFmClient target = new LastFmClient(api_key, api_secret, session_key);
     string track = "Ace Of Spades";
     string artist = "Motorhead";
     string album = String.Empty;
     string albumArtist = string.Empty;
     string context = string.Empty;
     Nullable<int> trackNumber = 2;
     string mbid = string.Empty;
     Nullable<int> duration = new Nullable<int>();
     TrackUpdateNowPlaying expected = new TrackUpdateNowPlaying()
     {
         Track = new CorrectedString("Ace Of Spades", 0),
         Artist = new CorrectedString("Motörhead", 1),
         Album = new CorrectedString(),
         AlbumArtist = new CorrectedString(),
         IgnoredMessage = new MessageWithCode(),
     };
     TrackUpdateNowPlaying actual;
     actual = target.TrackUpdateNowPlaying(track, artist, album, albumArtist, context, trackNumber, mbid, duration);
     Assert.IsTrue(ReflectionEqualityComparer.Default.Equals(expected, actual));
 }
Example #18
0
        public async Task NowPlaying(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"], (IGuildUser)command.Author);

                var client        = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);
                var topTracksTask = client.GetTopTracks(LastFmDataPeriod.Month, 100);
                var tracks        = (await client.GetRecentTracks(count: 1)).ToList();

                if (!tracks.Any())
                {
                    await command.Reply(GetNoScrobblesMessage((await command["User"].AsGuildUserOrName)?.Item2));

                    return;
                }

                var nowPlaying = tracks[0].NowPlaying;
                var current    = await client.GetTrackInfo(tracks[0].Artist.Name, tracks[0].Name);

                // Description
                var description = new StringBuilder();
                description.AppendLine($"**{FormatTrackLink(current ?? tracks[0].ToTrack())}** by **{FormatArtistLink(current?.Artist ?? tracks[0].Artist)}**");
                if (!string.IsNullOrEmpty(current?.Album?.Name))
                {
                    description.AppendLine($"On {DiscordHelpers.BuildMarkdownUri(current.Album.Name, current.Album.Url)}");
                }
                else if (!string.IsNullOrEmpty(tracks[0].Album?.Name))
                {
                    description.AppendLine($"On {tracks[0].Album.Name}");
                }

                var embed = new EmbedBuilder()
                            .WithDescription(description.ToString())
                            .WithColor(0xd9, 0x23, 0x23);

                // Image
                var imageUri = current?.Album?.ImageUri ?? tracks[0]?.Album?.ImageUri;
                if (imageUri != null)
                {
                    embed.WithThumbnailUrl(imageUri.AbsoluteUri);
                }

                // Title
                var author = new EmbedAuthorBuilder().WithIconUrl(_websiteWalker.LfIconUrl);
                if (!settings.Anonymous)
                {
                    author.WithUrl($"https://www.last.fm/user/{settings.LastFmUsername}");
                }

                if (nowPlaying)
                {
                    author.WithName($"{user} is now listening to...");
                }
                else
                {
                    author.WithName($"{user} last listened to...");
                }

                embed.WithAuthor(author);

                // Playcount
                var playCount = (current?.Playcount ?? 0) + (nowPlaying ? 1 : 0);
                if (playCount == 1 && current?.Playcount != null)
                {
                    embed.WithFooter($"First listen");
                }
                else if (playCount > 1)
                {
                    embed.WithFooter($"{playCount.ToEnglishOrdinal()} listen");
                }

                // Month placement
                {
                    var topTracks = await topTracksTask;

                    int counter = 0, placement = 0, placementPlaycount = int.MaxValue;
                    foreach (var track in topTracks)
                    {
                        counter++;
                        if (placementPlaycount > track.Playcount)
                        {
                            placementPlaycount = track.Playcount.Value;
                            placement          = counter;
                        }

                        if (string.Compare(track.Url, (string)(current?.Url ?? tracks[0].Url), true) == 0)
                        {
                            var footer = placement == 1 ? "Most played track this month" : $"{placement.ToEnglishOrdinal()} most played this month";
                            if (embed.Footer != null)
                            {
                                embed.Footer.Text += " • " + footer;
                            }
                            else
                            {
                                embed.WithFooter(footer);
                            }

                            break;
                        }
                    }
                }

                // Previous
                if (nowPlaying && tracks.Count > 1)
                {
                    var previous = tracks[1];
                    embed.AddField(x => x.WithName("Previous").WithValue($"{FormatTrackLink(previous?.ToTrack())} by {FormatArtistLink(previous?.Artist)}"));
                }

                await command.Reply(embed.Build());
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                ThrowUserNotFound((await command["User"].AsGuildUserOrName)?.Item2);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }
Example #19
0
 public void TrackUpdateNowPlayingTest3()
 {
     LastFmClient target = new LastFmClient(api_key, api_secret, session_key);
     string track = "Royale with cheese";
     string artist = "Various Artists";
     string album = "Pulp Fiction";
     string albumArtist = "John Travolta";
     string context = null;
     Nullable<int> trackNumber = 2;
     string mbid = string.Empty;
     Nullable<int> duration = new Nullable<int>();
     TrackUpdateNowPlaying expected = new TrackUpdateNowPlaying()
     {
         Track = new CorrectedString("Royale with cheese", 0),
         Artist = new CorrectedString("Various Artists", 0),
         Album = new CorrectedString("Pulp Fiction", 0),
         AlbumArtist = new CorrectedString("John Travolta", 0),
         IgnoredMessage = new MessageWithCode("Artist name failed filter: Various Artists", 1),
     };
     TrackUpdateNowPlaying actual;
     actual = target.TrackUpdateNowPlaying(track, artist, album, albumArtist, context, trackNumber, mbid, duration);
     Assert.IsTrue(ReflectionEqualityComparer.Default.Equals(expected, actual));
 }
Example #20
0
        public async Task LastFmRecent(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"], (IGuildUser)command.Author);

                var client = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);

                const int NumDisplayed = 100;
                var       userInfoTask = client.GetUserInfo();
                var       results      = await client.GetRecentTracks(count : NumDisplayed);

                if (!results.Any())
                {
                    throw new AbortException("This user hasn't scrobbled anything recently.");
                }

                var nowPlaying = results.First().NowPlaying;
                var pages      = new PageCollectionBuilder();
                var place      = 1;
                foreach (var track in results.Take(NumDisplayed))
                {
                    string when = null;
                    if (nowPlaying)
                    {
                        nowPlaying = false;
                        when       = "now playing";
                    }
                    else if (track.Timestamp.HasValue)
                    {
                        when = (track.Timestamp.Value - DateTimeOffset.UtcNow).SimpleFormat();
                    }

                    pages.AppendLine($"`{place++}>` **{FormatTrackLink(track.ToTrack(), true)}** by **{FormatArtistLink(track.Artist, true)}**" + (when != null ? $"_ – {when}_" : string.Empty));
                }

                var userInfo     = await userInfoTask;
                var embedFactory = new Func <EmbedBuilder>(() =>
                {
                    var author = new EmbedAuthorBuilder()
                                 .WithIconUrl(_websiteWalker.LfIconUrl)
                                 .WithName($"{user} last listened to...");

                    if (!settings.Anonymous)
                    {
                        author.WithUrl($"https://www.last.fm/user/{settings.LastFmUsername}");
                    }

                    var embed = new EmbedBuilder()
                                .WithColor(0xd9, 0x23, 0x23)
                                .WithAuthor(author);

                    if (userInfo?.Playcount != null)
                    {
                        embed.WithFooter($"{userInfo.Playcount} plays in total");
                    }

                    return(embed);
                });

                await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                ThrowUserNotFound((await command["User"].AsGuildUserOrName)?.Item2);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }
Example #21
0
        private void initializeScrobbler()
        {
            StartTimer();
            //StartMarqueeProgressBar();

            client = new LastFmClient();
            client.User = new LastFmUser();

            client.User.Username = userLogin;
            client.User.Password = userPassword;

            LastFmLib.WebRequests.Handshake handshake = client.Login();

            if (handshake.succeeded)
            {
                sm = client.GetScrobblerManager();
                scrobblerInit = true;

                if (ok.InvokeRequired)
                {
                    this.Invoke((MethodInvoker)delegate()
                    {
                           ok.Text = "Confirmed!";
                           optionsPopup.Show(new Point(this.Size.Width + this.Location.X, this.Location.Y + this.Size.Height / 3));
                    });
                }
                else ok.Text = "Cofirmed!";
            }
            else
            {
                if (ok.InvokeRequired)
                {
                    this.Invoke((MethodInvoker)delegate()
                    {
                        ok.Text = "Failed!\n (" + handshake.errorMessage + ")";
                        ok.Size = new Size(ok.Size.Width, ok.Size.Height * 2);
                        panel.Size = new Size(panel.Width, panel.Height + ok.Size.Height / 2);
                        optionsPopup.Show(new Point(this.Size.Width + this.Location.X, this.Location.Y + this.Size.Height / 3));
                    });
                }
                else ok.Text = "Failed!";
            }

            StopTimer();
            StopMarqueeProgressBar();
        }
Example #22
0
        public async Task LastFmArtist(ICommand command)
        {
            try
            {
                var(settings, user) = await GetLastFmSettings(command["User"].HasValue?await command["User"].AsGuildUser : (IGuildUser)command.Author, command["User"].HasValue);

                var period = command["Period"].HasValue ? ParseStatsPeriod(command["Period"]) : LastFmDataPeriod.Overall;
                if (period == LastFmDataPeriod.Day)
                {
                    throw new IncorrectParametersCommandException("The `day` value can't be used with this command.", false);
                }

                var client = new LastFmClient(settings.LastFmUsername, _integrationOptions.Value.LastFmKey);

                const int NumDisplayed = 10;
                var       info         = await client.GetArtistDetail(command["Artist"], period);

                if (info == null)
                {
                    await command.ReplyError("Can't find this artist or user. Make sure you're using the same spelling as the artist's page on Last.fm.");

                    return;
                }

                var author = new EmbedAuthorBuilder()
                             .WithIconUrl(_websiteWalker.LfIconUrl)
                             .WithName($"{user}'s stats for {info.Name}");

                if (!settings.Anonymous)
                {
                    author.WithUrl($"https://www.last.fm/user/{settings.LastFmUsername}");
                }

                var description = new StringBuilder();
                description.AppendLine($"You've listened to this artist **{info.Playcount}** times.");
                description.AppendLine($"You've heard **{info.AlbumsListened}** of their albums and **{info.TracksListened}** of their tracks.");

                var embed = new EmbedBuilder()
                            .WithDescription(description.ToString())
                            .WithColor(0xd9, 0x23, 0x23)
                            .WithAuthor(author)
                            .WithFooter($"Based on {FormatStatsDataPeriod(period)}");

                if (info.ImageUri != null)
                {
                    embed.WithThumbnailUrl(info.ImageUri.AbsoluteUri);
                }

                if (info.TopAlbums.Any())
                {
                    var topList = new StringBuilder();
                    var place   = 1;
                    foreach (var entry in info.TopAlbums.Take(NumDisplayed))
                    {
                        topList.TryAppendLineLimited($"`#{place++}` **{FormatAlbumLink(entry, true)}**_ – {entry.Playcount} plays_", DiscordHelpers.MaxEmbedFieldLength);
                    }

                    embed.AddField("Top albums", topList.ToString());
                }

                if (info.TopTracks.Any())
                {
                    var topList = new StringBuilder();
                    var place   = 1;
                    foreach (var entry in info.TopTracks.Take(NumDisplayed))
                    {
                        topList.TryAppendLineLimited($"`#{place++}` **{FormatTrackLink(entry, true)}**_ – {entry.Playcount} plays_", DiscordHelpers.MaxEmbedFieldLength);
                    }

                    embed.AddField("Top tracks", topList.ToString());
                }

                await command.Reply(embed.Build());
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
            {
                ThrowUserNotFound((await command["User"].AsGuildUserOrName)?.Item2);
            }
            catch (WebException e) when((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
            {
                throw new CommandException("The bot can't access your recently listened tracks. \n\nPlease make sure you don't have `Hide recent listening information` checked in your Last.fm settings (Settings -> Privacy -> Recent listening).");
            }
            catch (WebException e)
            {
                await command.Reply($"Last.fm is down (error {(e.Response as HttpWebResponse)?.StatusCode.ToString() ?? e.Status.ToString()}). Please try again in a few seconds.");
            }
        }