private void OnNowPlayingResponse(IAsyncResult ar) { try { current_now_playing_request.EndSend(ar); } catch (Exception e) { Log.Exception("Failed to complete the NowPlaying request", e); state = State.Idle; current_now_playing_request = null; return; } StationError error = current_now_playing_request.GetError(); // API docs say "Now Playing requests that fail should not be retried". if (error == StationError.InvalidSessionKey) { Log.Warning("Audioscrobbler NowPlaying failed", "Session ID sent was invalid", false); // TODO: Suggest to the user to (re)do the Last.fm authentication ? } else if (error != StationError.None) { Log.WarningFormat("Audioscrobbler NowPlaying failed: {0}", error.ToString()); } else { Log.Debug("Submitted NowPlaying track to Audioscrobbler"); now_playing_started = false; } current_now_playing_request = null; }
public StationError FetchSessionKey() { if (authentication_token == null) { return(StationError.TokenNotAuthorized); } try { LastfmRequest get_session = new LastfmRequest("auth.getSession", RequestType.SessionRequest, ResponseFormat.Json); get_session.AddParameter("token", authentication_token); get_session.Send(); var response = get_session.GetResponseObject(); object error_code; if (response.TryGetValue("error", out error_code)) { Log.WarningFormat("Lastfm error {0} : {1}", (int)error_code, (string)response["message"]); return((StationError)error_code); } var session = (Hyena.Json.JsonObject)response["session"]; UserName = (string)session["name"]; SessionKey = (string)session["key"]; Subscriber = session["subscriber"].ToString().Equals("1"); // The authentication token is only valid once, and for a limited time authentication_token = null; return(StationError.None); } catch (Exception e) { Log.Exception("Error in Lastfm.Account.FetchSessionKey", e); return(StationError.Unknown); } }
public void NowPlaying(string artist, string title, string album, double duration, int tracknum, string mbrainzid) { if (String.IsNullOrEmpty(artist) || String.IsNullOrEmpty(title) || !connected) { return; } // FIXME: need a lock for this flag if (now_playing_started) { return; } now_playing_started = true; string str_track_number = String.Empty; if (tracknum != 0) { str_track_number = tracknum.ToString(); } LastfmRequest request = new LastfmRequest("track.updateNowPlaying", RequestType.Write, ResponseFormat.Json); request.AddParameter("track", title); request.AddParameter("artist", artist); request.AddParameter("album", album); request.AddParameter("trackNumber", str_track_number); request.AddParameter("duration", Math.Floor(duration).ToString()); request.AddParameter("mbid", mbrainzid); current_now_playing_request = request; NowPlaying(current_now_playing_request); }
public StationError ChangeStationTo(string station) { lock (this) { if (Station == station) { return(StationError.None); } try { LastfmRequest radio_tune = new LastfmRequest("radio.tune", RequestType.Write, ResponseFormat.Json); radio_tune.AddParameter("station", station); radio_tune.Send(); StationError error = radio_tune.GetError(); if (error != StationError.None) { return(error); } this.station = station; return(StationError.None); } catch (Exception e) { Log.Error(e); return(StationError.Unknown); } } }
private void NowPlaying(LastfmRequest request) { try { request.BeginSend(OnNowPlayingResponse); } catch (Exception e) { Log.Warning("Audioscrobbler NowPlaying failed", String.Format("Failed to post NowPlaying: {0}", e), false); } }
private void TransmitQueue() { // save here in case we're interrupted before we complete // the request. we save it again when we get an OK back // from the server queue.Save(); next_interval = DateTime.MinValue; if (!connected) { return; } current_scrobble_request = new LastfmRequest("track.scrobble", RequestType.Write, ResponseFormat.Json); IList <IQueuedTrack> tracks = queue.GetTracks(); for (int i = 0; i < tracks.Count; i++) { IQueuedTrack track = tracks[i]; string str_track_number = String.Empty; if (track.TrackNumber != 0) { str_track_number = track.TrackNumber.ToString(); } bool chosen_by_user = (track.TrackAuth.Length == 0); current_scrobble_request.AddParameter(String.Format("timestamp[{0}]", i), track.StartTime.ToString()); current_scrobble_request.AddParameter(String.Format("track[{0}]", i), track.Title); current_scrobble_request.AddParameter(String.Format("artist[{0}]", i), track.Artist); current_scrobble_request.AddParameter(String.Format("album[{0}]", i), track.Album); current_scrobble_request.AddParameter(String.Format("trackNumber[{0}]", i), str_track_number); current_scrobble_request.AddParameter(String.Format("duration[{0}]", i), track.Duration.ToString()); current_scrobble_request.AddParameter(String.Format("mbid[{0}]", i), track.MusicBrainzId); current_scrobble_request.AddParameter(String.Format("chosenByUser[{0}]", i), chosen_by_user ? "1" : "0"); } Log.DebugFormat("Last.fm scrobbler sending '{0}'", current_scrobble_request.ToString()); state = State.Transmitting; current_async_result = current_scrobble_request.BeginSend(OnScrobbleResponse, tracks.Count); state = State.WaitingForResponse; if (!(current_async_result.AsyncWaitHandle.WaitOne(TIME_OUT, false))) { Log.Warning("Audioscrobbler upload failed", "The request timed out and was aborted", false); next_interval = DateTime.Now + new TimeSpan(0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; } }
private void TransmitQueue() { // save here in case we're interrupted before we complete // the request. we save it again when we get an OK back // from the server queue.Save(); next_interval = DateTime.MinValue; if (!connected) { return; } state = State.Transmitting; current_scrobble_request = new LastfmRequest("track.scrobble", RequestType.Write, ResponseFormat.Json); int trackCount = 0; while (true) { IQueuedTrack track = queue.GetNextTrack(); if (track == null || // Last.fm can technically handle up to 50 songs in one request // but let's not use the top limit trackCount == 40) { break; } try { current_scrobble_request.AddParameters(GetTrackParameters(track, trackCount)); trackCount++; } catch (MaxSizeExceededException) { break; } } Log.DebugFormat("Last.fm scrobbler sending '{0}'", current_scrobble_request.ToString()); current_async_result = current_scrobble_request.BeginSend(OnScrobbleResponse, trackCount); state = State.WaitingForResponse; if (!(current_async_result.AsyncWaitHandle.WaitOne(TIME_OUT, false))) { Log.Warning("Audioscrobbler upload failed", "The request timed out and was aborted", false); next_interval = DateTime.Now + new TimeSpan(0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; } }
private bool PostTrackRequest(string method, string artist, string title) { if (State != ConnectionState.Connected) { return(false); } // track.love and track.ban do not return JSON LastfmRequest track_request = new LastfmRequest(String.Concat("track.", method), RequestType.Write, ResponseFormat.Raw); track_request.AddParameter("track", title); track_request.AddParameter("artist", artist); track_request.Send(); return(track_request.GetError() == StationError.None); }
public StationError RequestAuthorization() { LastfmRequest get_token = new LastfmRequest("auth.getToken", RequestType.Read, ResponseFormat.Json); get_token.Send(); var response = get_token.GetResponseObject(); object error_code; if (response.TryGetValue("error", out error_code)) { Log.WarningFormat("Lastfm error {0} : {1}", (int)error_code, (string)response["message"]); return((StationError)error_code); } authentication_token = (string)response["token"]; Browser.Open(String.Format("http://www.last.fm/api/auth?api_key={0}&token={1}", LastfmCore.ApiKey, authentication_token)); return(StationError.None); }
public Playlist LoadPlaylistFor(string station) { lock (this) { if (station != Station) { return(null); } Playlist pl = new Playlist(); Stream stream = null; LastfmRequest radio_playlist = new LastfmRequest("radio.getPlaylist", RequestType.AuthenticatedRead, ResponseFormat.Raw); try { radio_playlist.Send(); stream = radio_playlist.GetResponseStream(); pl.Load(stream); Log.Debug(String.Format("Adding {0} Tracks to Last.fm Station {1}", pl.TrackCount, station), null); } catch (System.Net.WebException e) { Log.Warning("Error Loading Last.fm Station", e.Message, false); return(null); } catch (Exception e) { string body = null; try { using (StreamReader strm = new StreamReader(stream)) { body = strm.ReadToEnd(); } } catch {} Log.Warning( "Error loading station", String.Format("Exception:\n{0}\n\nResponse:\n{1}", e.ToString(), body ?? "Unable to get response"), false ); return(null); } return(pl); } }
public StationError FetchSessionKey () { if (authentication_token == null) { return StationError.TokenNotAuthorized; } try { LastfmRequest get_session = new LastfmRequest ("auth.getSession", RequestType.SessionRequest, ResponseFormat.Json); get_session.AddParameter ("token", authentication_token); get_session.Send (); var response = get_session.GetResponseObject (); object error_code; if (response.TryGetValue ("error", out error_code)) { Log.WarningFormat ("Lastfm error {0} : {1}", (int)error_code, (string)response["message"]); return (StationError) error_code; } var session = (Hyena.Json.JsonObject)response["session"]; UserName = (string)session["name"]; SessionKey = (string)session["key"]; Subscriber = session["subscriber"].ToString ().Equals ("1"); // The authentication token is only valid once, and for a limited time authentication_token = null; return StationError.None; } catch (Exception e) { Log.Exception ("Error in Lastfm.Account.FetchSessionKey", e); return StationError.Unknown; } }
private void NowPlaying(LastfmRequest request) { try { request.BeginSend (OnNowPlayingResponse); } catch (Exception e) { Log.Warning ("Audioscrobbler NowPlaying failed", String.Format("Failed to post NowPlaying: {0}", e), false); } }
private bool PostTrackRequest (string method, string artist, string title) { if (State != ConnectionState.Connected) return false; // track.love and track.ban do not return JSON LastfmRequest track_request = new LastfmRequest (String.Concat ("track.", method), RequestType.Write, ResponseFormat.Raw); track_request.AddParameter ("track", title); track_request.AddParameter ("artist", artist); track_request.Send (); return (track_request.GetError () == StationError.None); }
public Playlist LoadPlaylistFor (string station) { lock (this) { if (station != Station) return null; Playlist pl = new Playlist (); Stream stream = null; LastfmRequest radio_playlist = new LastfmRequest ("radio.getPlaylist", RequestType.AuthenticatedRead, ResponseFormat.Raw); try { radio_playlist.Send (); stream = radio_playlist.GetResponseStream (); pl.Load (stream); Log.Debug (String.Format ("Adding {0} Tracks to Last.fm Station {1}", pl.TrackCount, station), null); } catch (System.Net.WebException e) { Log.Warning ("Error Loading Last.fm Station", e.Message, false); return null; } catch (Exception e) { string body = null; try { using (StreamReader strm = new StreamReader (stream)) { body = strm.ReadToEnd (); } } catch {} Log.Warning ( "Error loading station", String.Format ("Exception:\n{0}\n\nResponse:\n{1}", e.ToString (), body ?? "Unable to get response"), false ); return null; } return pl; } }
public StationError ChangeStationTo (string station) { lock (this) { if (Station == station) return StationError.None; try { LastfmRequest radio_tune = new LastfmRequest ("radio.tune", RequestType.Write, ResponseFormat.Json); radio_tune.AddParameter ("station", station); radio_tune.Send (); StationError error = radio_tune.GetError (); if (error != StationError.None) { return error; } this.station = station; return StationError.None; } catch (Exception e) { Log.Exception (e); return StationError.Unknown; } } }
void GetMoreInfo(TrackInfo track) { var request = new LastfmRequest ("track.getInfo"); request.AddParameter ("artist", track.ArtistName); request.AddParameter ("track", track.TrackTitle); request.AddParameter ("mbid", track.MusicBrainzId); request.Send (); var response = request.GetResponseObject (); if (response == null) return; try { var json_track = (JsonObject)response["track"]; //track.Duration = TimeSpan.FromMilliseconds (double.Parse ((string)json_track["duration"])); if (!json_track.ContainsKey("album")) return; var json_album = (JsonObject)json_track["album"]; if (json_album != null) { var attr = (JsonObject)json_album["@attr"]; int pos = 0; if (int.TryParse ((string)attr["position"], out pos)) { track.TrackNumber = pos; } track.AlbumTitle = (string)json_album["title"]; track.AlbumMusicBrainzId = (string)json_album["mbid"]; track.AlbumArtist = (string)json_album["artist"]; } } catch (Exception e) { Log.DebugException (e); response.Dump (); } }
void FetchMetadata(TrackInfo track, int fpid) { var request = new LastfmRequest ("track.getFingerprintMetadata"); request.AddParameter ("fingerprintid", fpid.ToString ()); request.Send (); var response = request.GetResponseObject (); if (response == null) return; var json_tracks = (JsonObject)response["tracks"]; var obj_track = json_tracks["track"]; JsonObject json_track = null; if (obj_track is JsonArray) json_track = (JsonObject) (((JsonArray)obj_track)[0]); else if (obj_track is JsonObject) json_track = (JsonObject)obj_track; if (json_track !=null) { track.TrackTitle = (string)json_track["name"]; track.MusicBrainzId = (string)json_track["mbid"]; track.MoreInfoUri = new SafeUri ((string)json_track["url"]); var json_artist = (JsonObject)json_track["artist"]; if (json_artist != null) { track.ArtistName = (string)json_artist["name"]; track.ArtistMusicBrainzId = (string)json_artist["mbid"]; } GetMoreInfo (track); track.Update (); if (track == ServiceManager.PlayerEngine.CurrentTrack) ServiceManager.PlayerEngine.TrackInfoUpdated (); } }
public void NowPlaying(string artist, string title, string album, double duration, int tracknum, string mbrainzid) { if (String.IsNullOrEmpty (artist) || String.IsNullOrEmpty (title) || !connected) { return; } // FIXME: need a lock for this flag if (now_playing_started) { return; } now_playing_started = true; string str_track_number = String.Empty; if (tracknum != 0) { str_track_number = tracknum.ToString(); } LastfmRequest request = new LastfmRequest ("track.updateNowPlaying", RequestType.Write, ResponseFormat.Json); request.AddParameter ("track", title); request.AddParameter ("artist", artist); request.AddParameter ("album", album); request.AddParameter ("trackNumber", str_track_number); request.AddParameter ("duration", Math.Floor (duration).ToString ()); request.AddParameter ("mbid", mbrainzid); current_now_playing_request = request; NowPlaying (current_now_playing_request); }
private void OnNowPlayingResponse(IAsyncResult ar) { try { current_now_playing_request.EndSend (ar); } catch (Exception e) { Log.Exception ("Failed to complete the NowPlaying request", e); state = State.Idle; current_now_playing_request = null; return; } StationError error = current_now_playing_request.GetError (); // API docs say "Now Playing requests that fail should not be retried". if (error == StationError.InvalidSessionKey) { Log.Warning ("Audioscrobbler NowPlaying failed", "Session ID sent was invalid", false); // TODO: Suggest to the user to (re)do the Last.fm authentication ? } else if (error != StationError.None) { Log.WarningFormat ("Audioscrobbler NowPlaying failed: {0}", error.ToString ()); } else { Log.Debug ("Submitted NowPlaying track to Audioscrobbler"); now_playing_started = false; } current_now_playing_request = null; }
private void TransmitQueue() { // save here in case we're interrupted before we complete // the request. we save it again when we get an OK back // from the server queue.Save (); next_interval = DateTime.MinValue; if (!connected) { return; } state = State.Transmitting; current_scrobble_request = new LastfmRequest ("track.scrobble", RequestType.Write, ResponseFormat.Json); int trackCount = 0; while (true) { IQueuedTrack track = queue.GetNextTrack (); if (track == null || // Last.fm can technically handle up to 50 songs in one request // but let's not use the top limit trackCount == 40) { break; } try { current_scrobble_request.AddParameters (GetTrackParameters (track, trackCount)); trackCount++; } catch (MaxSizeExceededException) { break; } } Log.DebugFormat ("Last.fm scrobbler sending '{0}'", current_scrobble_request.ToString ()); current_async_result = current_scrobble_request.BeginSend (OnScrobbleResponse, trackCount); state = State.WaitingForResponse; if (!(current_async_result.AsyncWaitHandle.WaitOne (TIME_OUT, false))) { Log.Warning ("Audioscrobbler upload failed", "The request timed out and was aborted", false); next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; } }
public StationError RequestAuthorization () { try { LastfmRequest get_token = new LastfmRequest ("auth.getToken", RequestType.Read, ResponseFormat.Json); get_token.Send (); var response = get_token.GetResponseObject (); object error_code; if (response.TryGetValue ("error", out error_code)) { Log.WarningFormat ("Lastfm error {0} : {1}", (int)error_code, (string)response["message"]); return (StationError) error_code; } authentication_token = (string)response["token"]; Browser.Open (String.Format ("http://www.last.fm/api/auth?api_key={0}&token={1}", LastfmCore.ApiKey, authentication_token)); return StationError.None; } catch (Exception e) { Log.Exception ("Error in Lastfm.Account.RequestAuthorization", e); return StationError.Unknown; } }
private void TransmitQueue () { // save here in case we're interrupted before we complete // the request. we save it again when we get an OK back // from the server queue.Save (); next_interval = DateTime.MinValue; if (!connected) { return; } current_scrobble_request = new LastfmRequest ("track.scrobble", RequestType.Write, ResponseFormat.Json); IList<IQueuedTrack> tracks = queue.GetTracks (); for (int i = 0; i < tracks.Count; i++) { IQueuedTrack track = tracks[i]; string str_track_number = String.Empty; if (track.TrackNumber != 0) { str_track_number = track.TrackNumber.ToString(); } bool chosen_by_user = (track.TrackAuth.Length == 0); current_scrobble_request.AddParameter (String.Format ("timestamp[{0}]", i), track.StartTime.ToString ()); current_scrobble_request.AddParameter (String.Format ("track[{0}]", i), track.Title); current_scrobble_request.AddParameter (String.Format ("artist[{0}]", i), track.Artist); current_scrobble_request.AddParameter (String.Format ("album[{0}]", i), track.Album); current_scrobble_request.AddParameter (String.Format ("trackNumber[{0}]", i), str_track_number); current_scrobble_request.AddParameter (String.Format ("duration[{0}]", i), track.Duration.ToString ()); current_scrobble_request.AddParameter (String.Format ("mbid[{0}]", i), track.MusicBrainzId); current_scrobble_request.AddParameter (String.Format ("chosenByUser[{0}]", i), chosen_by_user ? "1" : "0"); } Log.DebugFormat ("Last.fm scrobbler sending '{0}'", current_scrobble_request.ToString ()); state = State.Transmitting; current_async_result = current_scrobble_request.BeginSend (OnScrobbleResponse, tracks.Count); state = State.WaitingForResponse; if (!(current_async_result.AsyncWaitHandle.WaitOne (TIME_OUT, false))) { Log.Warning ("Audioscrobbler upload failed", "The request timed out and was aborted", false); next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; } }