public void GetSession_UnAuthorisedToken_ThrowsException()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret);

            // Act
            string session = scrobbler.GetSession();

            // Assert
            Assert.IsNotNull(session);
        }
예제 #2
0
파일: Plugin.cs 프로젝트: MrSm1th/lastfm
        public override void Initialize()
        {
            scrobblingSettings = ScrobblingSettings.GetSettings();

            Logger.LogMessage("Settings loaded");

            scrobbler = new Scrobbler(scrobblingSettings);

            SetEventHandlers();

            Logger.LogMessage("Plugin initialized");
        }
        public void GetAuthorisationUri_TestApiKey_ReturnsWellFormedUri()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret);
            string expectedResult = string.Format(Scrobbler.RequestAuthorisationUriPattern, ApiKey, "");

            // Act
            string uri = scrobbler.GetAuthorisationUri();

            // Assert
            Assert.IsTrue(uri.StartsWith(expectedResult));
        }
        public void GetSession_AuthorisedToken_ReturnsSessionKey()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret);

            // break here and authorise via a browser
            string uri = scrobbler.GetAuthorisationUri();

            // Act
            string session = scrobbler.GetSession();

            // Assert
            Assert.IsNotNull(session);
        }
예제 #5
0
        public async Task ScrobblesMultiple()
        {
            var scrobbles = GenerateScrobbles(4);

            var countingHandler = new CountingHttpClientHandler();
            var httpClient      = new HttpClient(countingHandler);
            var scrobbler       = new Scrobbler(Lastfm.Auth, httpClient)
            {
                MaxBatchSize = 2
            };
            var response = await scrobbler.ScrobbleAsync(scrobbles);

            Assert.AreEqual(2, countingHandler.Count);
            Assert.AreEqual(LastResponseStatus.Successful, response.Status);
            Assert.IsTrue(response.Success);
        }
 /// <summary>
 /// Read the cached srobbles.
 /// </summary>
 public async Task GetCachedScrobbles()
 {
     try
     {
         EnableControls  = false;
         CachedScrobbles = new ObservableCollection <Scrobble>(await Scrobbler.GetCachedAsync());
     }
     catch (Exception ex)
     {
         OnStatusUpdated(string.Format("Fatal error getting cached scrobbles: {0}", ex.Message));
     }
     finally
     {
         EnableControls = true;
     }
 }
        public void NowPlaying_SessionKey_NoException()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret, SessionKey);
            var track = new Track
            {
                TrackName = "Spying Glass",
                AlbumArtist = "Massive Attack",
                ArtistName = "Massive Attack",
                AlbumName = "Protection",
                Duration = new TimeSpan(0, 0, 5, 21),
                TrackNumber = 5,
            };

            // Act
            var response = scrobbler.NowPlaying(track);
        }
예제 #8
0
        public void NowPlaying_SessionKey_NoException()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret, SessionKey);
            var track     = new Track
            {
                TrackName   = "Spying Glass",
                AlbumArtist = "Massive Attack",
                ArtistName  = "Massive Attack",
                AlbumName   = "Protection",
                Duration    = new TimeSpan(0, 0, 5, 21),
                TrackNumber = 5,
            };

            // Act
            var response = scrobbler.NowPlaying(track);
        }
예제 #9
0
        public MainWindow(SovndClient client, ChannelDirectory channels, IPlayerFactory playerFactory, ISettingsProvider settings, Scrobbler scrobbler)
        {
            InitializeComponent();

            toast = new Toast();
            toast.Show();

            _scrobbler     = scrobbler;
            _client        = client;
            _playerFactory = playerFactory;
            _settings      = settings.GetSettings();

            AllowDrop = true;
            channelbox.ItemsSource = channels.channels;

            PreviewDragOver  += OnPreviewDragEnter;
            PreviewDragEnter += OnPreviewDragEnter;
            DragEnter        += OnPreviewDragEnter;
            DragOver         += OnPreviewDragEnter;

            Drop += OnDrop;

            Loaded += (_, __) =>
            {
                BindingOperations.EnableCollectionSynchronization(channels.channels, channels.channels);
                App.WindowHandle = new WindowInteropHelper(this).Handle;
                synchronization  = SynchronizationContext.Current;

                _client.Run();

                if (!string.IsNullOrWhiteSpace(_settings.LastChannel))
                {
                    _player = _playerFactory.CreatePlayer(_settings.LastChannel);
                    _client.SubscribeToChannel(_settings.LastChannel);
                    SetupChannel();
                    Logging.Event("Switched to previously set channel");
                }
            };

            Closed += (_, __) =>
            {
                _client.Disconnect();
                Spotify.ShutDown();
                Process.GetCurrentProcess().Kill(); // TODO That's really inelegant
            };
        }
예제 #10
0
        private string GetSessionKey()
        {
            LoadSettings();

            // try get the session key from the registry
            string sessionKey = appSettings.Key;

            if (string.IsNullOrEmpty(sessionKey))
            {
                // instantiate a new scrobbler
                var scrobbler = new Scrobbler(ApiKey, ApiSecret);

                //NOTE: This is demo code. You would not normally do this in a production application
                while (string.IsNullOrEmpty(sessionKey))
                {
                    // Try get session key from Last.fm
                    try {
                        sessionKey = scrobbler.GetSession();

                        // successfully got a key. Save it to the registry for next time
                        appSettings.Key = sessionKey;
                        SaveSettings();
                        //SetRegistrySetting(sessionKeyRegistryKeyName, sessionKey);
                    }
                    catch (LastFmApiException exception) {
                        // get session key from Last.fm failed
                        //    Console.WriteLine(exception.Message);

                        // get a url to authenticate this application
                        string url = scrobbler.GetAuthorisationUri();

                        // open the URL in the default browser
                        Process.Start(url);

                        // To enable easy authorisation controlled by other application, this must be the first response.
                        // An external application can check whether authentication is needed by checking first responce to the message below
                        Console.WriteLine("[Authenticates] Press RETURN when application authenticated.");

                        Console.ReadLine();
                    }
                }
            }

            return(sessionKey);
        }
예제 #11
0
        public async void ScrobbleTrack(string artist, string album, string track)
        {
            var        trackApi = new TrackApi(_auth);
            var        scrobble = new Scrobble(artist, album, track, DateTimeOffset.Now);
            IScrobbler _scrobbler;

            _scrobbler = new Scrobbler(_auth);
            var response = await _scrobbler.ScrobbleAsync(scrobble);

            if (response.Success)
            {
                Debug.WriteLine("Scrobble success!");
            }
            else
            {
                Debug.WriteLine("Scrobble failed!");
            }
        }
예제 #12
0
        /// <summary>
        /// Scrobbles the selected scrobbles.
        /// </summary>
        /// <returns>Task.</returns>
        public override async Task Scrobble()
        {
            EnableControls = false;
            OnStatusUpdated("Trying to scrobble selected tracks...");

            var response = await Scrobbler.ScrobbleAsync(CreateScrobbles());

            if (response.Success)
            {
                OnStatusUpdated("Successfully scrobbled!");
            }
            else
            {
                OnStatusUpdated("Error while scrobbling!");
            }

            EnableControls = true;
        }
        /// <summary>
        /// Scrobbles the currently playing track.
        /// </summary>
        /// <returns>Task.</returns>
        public override async Task Scrobble()
        {
            if (CanScrobble && !_currentResponse.Track.IsAd())
            {
                EnableControls = false;

                Scrobble s = null;
                try
                {
                    OnStatusUpdated($"Trying to scrobble '{CurrentTrackName}'...");
                    // lock while acquiring current data
                    lock (_lockAnchor)
                    {
                        s = new Scrobble(CurrentArtistName, CurrentAlbumName, CurrentTrackName, DateTime.Now)
                        {
                            Duration = TimeSpan.FromSeconds(CurrentTrackLength),
                        };
                    }

                    var response = await Scrobbler.ScrobbleAsync(s, true);

                    if (response.Success && response.Status == LastResponseStatus.Successful)
                    {
                        OnStatusUpdated($"Successfully scrobbled '{s.Track}'");
                    }
                    else if (response.Status == LastResponseStatus.Cached)
                    {
                        OnStatusUpdated($"Scrobbling '{s.Track}' failed. Scrobble has been cached");
                    }
                    else
                    {
                        OnStatusUpdated($"Error while scrobbling '{s.Track}': {response.Status}");
                    }
                }
                catch (Exception ex)
                {
                    OnStatusUpdated($"Fatal error while trying to scrobble '{s.Track}: {ex.Message}");
                }
                finally
                {
                    EnableControls = true;
                }
            }
        }
예제 #14
0
        private async void SyncScrobblesClick(object sender, RoutedEventArgs e)
        {
            var progress = await this.ShowProgressAsync("Syncing...", "Scrobbling selected tracks...");

            var scrobbles    = leftListView.SelectedItems.Cast <LastTrack>().ToList();
            var newScrobbles = scrobbles.Where(o => o.TimePlayed != null && !GinaScrobbles.Any(p => p.TimePlayed == o.TimePlayed));
            var list         = newScrobbles.Select(o => new Scrobble(o.ArtistName, o.AlbumName, o.Name, o.TimePlayed.Value)
            {
                ChosenByUser = true, Duration = o.Duration
            }).ToList();
            var scrobbler = new Scrobbler(client.Auth);
            var res       = await scrobbler.ScrobbleAsync(list);

            await progress.CloseAsync();

            await this.ShowMessageAsync("Syncing finished!", $"Synced {list.Count} scrobbles.");

            ReloadScrobbles();
        }
 /// <summary>
 /// Read the cached scrobbles.
 /// </summary>
 public async Task GetCachedScrobbles()
 {
     try
     {
         EnableControls = false;
         OnStatusUpdated("Trying to get cached scrobbles...");
         Scrobbles = new ObservableCollection <Scrobble>(await Scrobbler.GetCachedAsync());
         OnStatusUpdated(string.Format("Successfully got cached scrobbles ({0})", Scrobbles.Count));
     }
     catch (Exception ex)
     {
         Scrobbles.Clear();
         OnStatusUpdated(string.Format("Fatal error getting cached scrobbles: {0}", ex.Message));
     }
     finally
     {
         EnableControls = true;
     }
 }
예제 #16
0
        public void Scrobble_TestTrack_NoException()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret, SessionKey);
            var track     = new Track
            {
                TrackName   = "Spying Glass",
                AlbumArtist = "Massive Attack",
                ArtistName  = "Massive Attack",
                AlbumName   = "Protection",
                Duration    = new TimeSpan(0, 0, 5, 21),
                TrackNumber = 5,
            };

            track.WhenStartedPlaying = DateTime.Now.Subtract(track.Duration);

            // Act
            var response = scrobbler.Scrobble(track);
        }
        public void Scrobble_TestTrack_NoException()
        {
            // Arrange
            var scrobbler = new Scrobbler(ApiKey, ApiSecret, SessionKey);
            var track = new Track
            {
                TrackName = "Spying Glass",
                AlbumArtist = "Massive Attack",
                ArtistName = "Massive Attack",
                AlbumName = "Protection",
                Duration = new TimeSpan(0, 0, 5, 21),
                TrackNumber = 5,
            };

            track.WhenStartedPlaying = DateTime.Now.Subtract(track.Duration);

            // Act
            var response = scrobbler.Scrobble(track);

        }
예제 #18
0
        /// <summary>
        /// Scrobbles the currently playing track.
        /// </summary>
        /// <returns>Task.</returns>
        public override async Task Scrobble()
        {
            if (CanScrobble && !_currentResponse.Track.IsAd())
            {
                EnableControls = false;

                try
                {
                    OnStatusUpdated("Trying to scrobble currently playing track...");

                    Scrobble s = new Scrobble(CurrentArtistName, CurrentAlbumName, CurrentTrackName, DateTime.Now)
                    {
                        Duration = TimeSpan.FromSeconds(CurrentTrackLength),
                    };

                    var response = await Scrobbler.ScrobbleAsync(s);

                    if (response.Success && response.Status == LastResponseStatus.Successful)
                    {
                        OnStatusUpdated(string.Format("Successfully scrobbled {0}!", CurrentTrackName));
                    }
                    else if (response.Status == LastResponseStatus.Cached)
                    {
                        OnStatusUpdated(string.Format("Scrobbling of track {0} failed. Scrobble has been cached", CurrentTrackName));
                    }
                    else
                    {
                        OnStatusUpdated("Error while scrobbling: " + response.Status);
                    }
                }
                catch (Exception ex)
                {
                    OnStatusUpdated("Fatal error while trying to scrobble currently playing track. Error: " + ex.Message);
                }
                finally
                {
                    EnableControls = true;
                }
            }
        }
예제 #19
0
        public async Task CorrectResponseWhenRequestFailed()
        {
            var requestMessage = GenerateExpectedRequestMessage(TrackApiResponses.TrackScrobbleMultipleRequestBody);

            var testScrobbles    = GetTestScrobbles();
            var responseMessage  = TestHelper.CreateResponseMessage(HttpStatusCode.RequestTimeout, new byte[0]);
            var scrobbleResponse = await ExecuteTestInternal(testScrobbles, responseMessage, requestMessage);

            if (Scrobbler.CacheEnabled)
            {
                Assert.AreEqual(LastResponseStatus.Cached, scrobbleResponse.Status);

                // check actually cached
                var cached = await Scrobbler.GetCachedAsync();

                TestHelper.AssertSerialiseEqual(testScrobbles, cached);
            }
            else
            {
                Assert.AreEqual(LastResponseStatus.RequestFailed, scrobbleResponse.Status);
            }
        }
예제 #20
0
        protected async Task <ScrobbleResponse> ExecuteTestInternal(IEnumerable <Scrobble> testScrobbles, HttpResponseMessage responseMessage, HttpRequestMessage expectedRequestMessage = null)
        {
            FakeResponseHandler.Enqueue(responseMessage);

            var scrobbleResponse = await Scrobbler.ScrobbleAsync(testScrobbles);

            if (expectedRequestMessage != null)
            {
                var actualRequestMessage = FakeResponseHandler.Sent.First();
                TestHelper.AssertSerialiseEqual(expectedRequestMessage.Headers, actualRequestMessage.Item1.Headers);
                TestHelper.AssertSerialiseEqual(expectedRequestMessage.RequestUri, actualRequestMessage.Item1.RequestUri);

                var expectedRequestBody = await expectedRequestMessage.Content.ReadAsStringAsync();

                var actualRequestBody = actualRequestMessage.Item2;
                TestHelper.AssertSerialiseEqual(expectedRequestBody, actualRequestBody);
            }

            FakeResponseHandler.Sent.Clear();

            return(scrobbleResponse);
        }
예제 #21
0
        public YScrobbler()
        {
            try {
                /*
                 * // Set up the Scrobbler
                 * if (string.IsNullOrEmpty(ApiKey) || string.IsNullOrEmpty(ApiSecret))
                 * {
                 *  throw new InvalidOperationException(
                 *      "ApiKey and ApiSecret have not been set. Go to http://www.last.fm/api/account and apply for an API account. Then paste the key and secret into the constants on PlayerForm.cs");
                 * }*/

                string sessionKey = GetSessionKey();

                // instantiate the async scrobbler
                _scrobbler   = new Scrobbler(ApiKey, ApiSecret, sessionKey);
                CurrentTrack = new Track();
                Console.WriteLine("Ready.");
            }
            catch (Exception exception) {
                Console.WriteLine(exception.Message);
            }
        }
예제 #22
0
        public void Init()
        {
            if (Settings.Current.ScrobbleActive)
            {
                // instantiate a new scrobbler
                if (scrobbler == null)
                {
                    scrobbler = new Scrobbler(ApiKey, ApiSecret);
                }

                if (_scrobbler == null)
                {
                    string sessionKey = GetSessionKey();

                    if (!string.IsNullOrEmpty(sessionKey))
                    {
                        // instantiate the async scrobbler
                        _scrobbler = new QueuingScrobbler(ApiKey, ApiSecret, sessionKey);
                    }
                }
            }
        }
예제 #23
0
 public AuthScrobbler(ILastAuth auth, HttpClient httpClient = null)
 {
     _scrobbler = new Scrobbler(auth, httpClient);
 }
예제 #24
0
 public LastFMManager(PlayerSettings settings)
 {
     scrobbler = new Scrobbler(settings.LastFMApiKey, settings.LastFMApiSecret, settings.LastFMSessionKey);
 }
예제 #25
0
 public virtual void Cleanup()
 {
     Scrobbler.Dispose();
 }