async Task <bool> HasScrobbled(params string[] mediaFile) { await init.Login("", ""); Lastfm last = new Lastfm(); return(await last.Scrobble(init.Auth.Auth, mediaFile)); }
private void ResetClient() { if (sva != null) { try { sva.Dispose(); } catch (Exception ex) { Logger.Error(ex); } finally { sva = null; } } switch (pref.ScrobbleMethod) { case Preference.ScrobbleMethods.Standalone: if ((pref.Username != null && pref.password != null && pref.Username != "" && pref.password != "") || pref.Username != this.pref.Username) { pref.AuthToken = ""; try { var lastfm = new LuteaLastfm(); var result = lastfm.Auth_getMobileSession(pref.Username, pref.password); if (result) { pref.AuthToken = Lastfm.GenAuthToken(pref.Username, pref.password); } } catch (Exception e) { Logger.Error(e); } } if (pref.ScrobbleEnabled) { sva = new StandaloneLastfmClient(this); } break; case Preference.ScrobbleMethods.ViaLastfmApp: if (pref.ScrobbleEnabled) { sva = new ViaAppLastfmClient(); } break; } }
public Connection(string clientID, string clientVersion, string username, Lastfm.Services.Session authenticatedSession) { RequestParameters p = new RequestParameters(); p["hs"] = "true"; p["p"] = "1.2.1"; p["c"] = clientID; p["v"] = clientVersion; p["u"] = username; string timestamp = Utilities.DateTimeToUTCTimestamp(DateTime.Now).ToString(); p["t"] = timestamp; p["api_key"] = authenticatedSession.APIKey; p["sk"] = authenticatedSession.SessionKey; p["a"] = Utilities.md5(authenticatedSession.APISecret + timestamp); this.handshakeParameters = p; ClientID = clientID; }
public StandaloneLastfmClient(LastfmScrobble parent) { lastfm = new LuteaLastfm(); this.Parent = parent; }
/// <summary> /// Process returns an AlbumArtistsResponse containing a list of artists, albums, and songs /// </summary> public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Lists of artists, albums, songs to be returned via handler IList <AlbumArtist> albumArtists = new List <AlbumArtist>(); IList <Album> albums = new List <Album>(); IList <Song> songs = new List <Song>(); Dictionary <string, int> counts = new Dictionary <string, int>(); PairList <string, int> sectionPositions = new PairList <string, int>(); // Optional Last.fm info string lastfmInfo = null; // Check if an ID was passed if (uri.Id != null) { // Add artist by ID to the list AlbumArtist a = Injection.Kernel.Get <IAlbumArtistRepository>().AlbumArtistForId((int)uri.Id); albumArtists.Add(a); // Add artist's albums to response albums = a.ListOfAlbums(); counts.Add("albums", albums.Count); // If requested, add artist's songs to response if (uri.Parameters.ContainsKey("includeSongs") && uri.Parameters["includeSongs"].IsTrue()) { songs = a.ListOfSongs(); counts.Add("songs", songs.Count); } else { counts.Add("songs", a.ListOfSongs().Count); } // If requested, add artist's Last.fm info to response if (uri.Parameters.ContainsKey("lastfmInfo") && uri.Parameters["lastfmInfo"].IsTrue()) { logger.IfInfo("Querying Last.fm for artist: " + a.AlbumArtistName); try { lastfmInfo = Lastfm.GetAlbumArtistInfo(a); logger.IfInfo("Last.fm query complete!"); } catch (Exception e) { logger.Error("Last.fm query failed!"); logger.Error(e); } } // Get favorites count if available if (a.AlbumArtistId != null) { int favoriteCount = Injection.Kernel.Get <IFavoriteRepository>().FavoritesForAlbumArtistId(a.AlbumArtistId, user.UserId).Count; counts.Add("favorites", favoriteCount); } else { counts.Add("favorites", 0); } } // Check for a request for range of artists else if (uri.Parameters.ContainsKey("range")) { string[] range = uri.Parameters["range"].Split(','); // Ensure valid range was parsed if (range.Length != 2) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'range' requires a valid, comma-separated character tuple", null, null, null, null, null, null)); return; } // Validate as characters char start, end; if (!Char.TryParse(range[0], out start) || !Char.TryParse(range[1], out end)) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'range' requires characters which are single alphanumeric values", null, null, null, null, null, null)); return; } // Grab range of artists albumArtists = Injection.Kernel.Get <IAlbumArtistRepository>().RangeAlbumArtists(start, end); } // Check for a request to limit/paginate artists, like SQL // Note: can be combined with range or all artists if (uri.Parameters.ContainsKey("limit") && uri.Id == null) { string[] limit = uri.Parameters["limit"].Split(','); // Ensure valid limit was parsed if (limit.Length < 1 || limit.Length > 2) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'limit' requires a single integer, or a valid, comma-separated integer tuple", null, null, null, null, null, null)); return; } // Validate as integers int index = 0; int duration = Int32.MinValue; if (!Int32.TryParse(limit[0], out index)) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'limit' requires a valid integer start index", null, null, null, null, null, null)); return; } // Ensure positive index if (index < 0) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'limit' requires a non-negative integer start index", null, null, null, null, null, null)); return; } // Check for duration if (limit.Length == 2) { if (!Int32.TryParse(limit[1], out duration)) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'limit' requires a valid integer duration", null, null, null, null, null, null)); return; } // Ensure positive duration if (duration < 0) { processor.WriteJson(new AlbumArtistsResponse("Parameter 'limit' requires a non-negative integer duration", null, null, null, null, null, null)); return; } } // Check if results list already populated by range if (albumArtists.Count > 0) { // No duration? Return just specified number of artists if (duration == Int32.MinValue) { albumArtists = albumArtists.Skip(0).Take(index).ToList(); } else { // Else, return artists starting at index, up to count duration albumArtists = albumArtists.Skip(index).Take(duration).ToList(); } } else { // If no artists in list, grab directly using model method albumArtists = Injection.Kernel.Get <IAlbumArtistRepository>().LimitAlbumArtists(index, duration); } } // Finally, if no artists already in list, send the whole list if (albumArtists.Count == 0) { albumArtists = Injection.Kernel.Get <IAlbumArtistRepository>().AllAlbumArtists(); sectionPositions = Utility.SectionPositionsFromSortedList(new List <IGroupingItem>(albumArtists.Select(c => (IGroupingItem)c))); } // Send it! processor.WriteJson(new AlbumArtistsResponse(null, albumArtists, albums, songs, counts, lastfmInfo, sectionPositions)); return; }
/// <summary> /// Process a Last.fm API request /// </summary> public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Create Last.fm object for this user Lastfm lfm = new Lastfm(user); // Pull URL parameters for Last.fm integration string eve = null; uri.Parameters.TryGetValue("event", out eve); if (uri.Action == null || uri.Action == "auth") { // If not authenticated, pass back authorization URL if (!lfm.SessionAuthenticated) { processor.WriteJson(new ScrobbleResponse(null, lfm.AuthUrl)); } else { // Else, already authenticated processor.WriteJson(new ScrobbleResponse("LFMAlreadyAuthenticated")); } return; } // If Last.fm is not authenticated, provide an authorization URL if (!lfm.SessionAuthenticated) { logger.IfInfo("You must authenticate before you can scrobble."); processor.WriteJson(new ScrobbleResponse("LFMNotAuthenticated", lfm.AuthUrl)); return; } // Create list of scrobble data IList <LfmScrobbleData> scrobbles = new List <LfmScrobbleData>(); // Get Last.fm API enumerations LfmScrobbleType scrobbleType = Lastfm.ScrobbleTypeForString(uri.Action); // On invalid scrobble type, return error JSON if (scrobbleType == LfmScrobbleType.INVALID) { processor.WriteJson(new ScrobbleResponse("LFMInvalidScrobbleType")); return; } // On now playing scrobble type if (scrobbleType == LfmScrobbleType.NOWPLAYING) { // Ensure ID specified for scrobble if (uri.Id == null) { processor.WriteJson(new ScrobbleResponse("LFMNoIdSpecifiedForNowPlaying")); return; } // Add successful scrobble to list, submit scrobbles.Add(new LfmScrobbleData((int)uri.Id, null)); lfm.Scrobble(scrobbles, scrobbleType); } // Else, unknown scrobble event else { // On null event, return error JSON if (eve == null) { processor.WriteJson(new ScrobbleResponse("LFMNoEventSpecifiedForScrobble")); return; } // Ensure input is a comma-separated pair string[] input = eve.Split(','); if ((input.Length % 2) != 0) { processor.WriteJson(new ScrobbleResponse("LFMInvalidInput")); return; } // Add scrobbles from input data pairs int i = 0; while (i < input.Length) { scrobbles.Add(new LfmScrobbleData(int.Parse(input[i]), long.Parse(input[i + 1]))); i = i + 2; } } // Scrobble all plays string result = lfm.Scrobble(scrobbles, scrobbleType); dynamic resp = null; // No response, service must be offline if (result == null) { processor.WriteJson(new ScrobbleResponse("LFMServiceOffline")); return; } // If result is not null, store deserialize and store it try { resp = JsonConvert.DeserializeObject(result); } catch (Exception e) { logger.Error(e); } // Check for nowplaying or scrobbles fields if ((resp.nowplaying != null) || (resp.scrobbles != null)) { // Write blank scrobble response processor.WriteJson(new ScrobbleResponse()); return; } // Write error JSON if it exists else if (resp.error != null) { processor.WriteJson(new ScrobbleResponse(string.Format("LFM{0}: {1}", resp.error, resp.message))); return; } }
/// <summary> /// Process a Last.fm API request /// </summary> public void Process(UriWrapper uri, IHttpProcessor processor, User user) { // Create Last.fm object for this user Lastfm lfm = new Lastfm(user); // Pull URL parameters for Last.fm integration string eve = null; uri.Parameters.TryGetValue("event", out eve); if (uri.Action == null || uri.Action == "auth") { // If not authenticated, pass back authorization URL if (!lfm.SessionAuthenticated) { processor.WriteJson(new ScrobbleResponse(null, lfm.AuthUrl)); } else { // Else, already authenticated processor.WriteJson(new ScrobbleResponse("LFMAlreadyAuthenticated")); } return; } // If Last.fm is not authenticated, provide an authorization URL if (!lfm.SessionAuthenticated) { logger.IfInfo("You must authenticate before you can scrobble."); processor.WriteJson(new ScrobbleResponse("LFMNotAuthenticated", lfm.AuthUrl)); return; } // Create list of scrobble data IList<LfmScrobbleData> scrobbles = new List<LfmScrobbleData>(); // Get Last.fm API enumerations LfmScrobbleType scrobbleType = Lastfm.ScrobbleTypeForString(uri.Action); // On invalid scrobble type, return error JSON if (scrobbleType == LfmScrobbleType.INVALID) { processor.WriteJson(new ScrobbleResponse("LFMInvalidScrobbleType")); return; } // On now playing scrobble type if (scrobbleType == LfmScrobbleType.NOWPLAYING) { // Ensure ID specified for scrobble if (uri.Id == null) { processor.WriteJson(new ScrobbleResponse("LFMNoIdSpecifiedForNowPlaying")); return; } // Add successful scrobble to list, submit scrobbles.Add(new LfmScrobbleData((int)uri.Id, null)); lfm.Scrobble(scrobbles, scrobbleType); } // Else, unknown scrobble event else { // On null event, return error JSON if (eve == null) { processor.WriteJson(new ScrobbleResponse("LFMNoEventSpecifiedForScrobble")); return; } // Ensure input is a comma-separated pair string[] input = eve.Split(','); if ((input.Length % 2) != 0) { processor.WriteJson(new ScrobbleResponse("LFMInvalidInput")); return; } // Add scrobbles from input data pairs int i = 0; while (i < input.Length) { scrobbles.Add(new LfmScrobbleData(int.Parse(input[i]), long.Parse(input[i + 1]))); i = i + 2; } } // Scrobble all plays string result = lfm.Scrobble(scrobbles, scrobbleType); dynamic resp = null; // No response, service must be offline if (result == null) { processor.WriteJson(new ScrobbleResponse("LFMServiceOffline")); return; } // If result is not null, store deserialize and store it try { resp = JsonConvert.DeserializeObject(result); } catch (Exception e) { logger.Error(e); } // Check for nowplaying or scrobbles fields if ((resp.nowplaying != null) || (resp.scrobbles != null)) { // Write blank scrobble response processor.WriteJson(new ScrobbleResponse()); return; } // Write error JSON if it exists else if (resp.error != null) { processor.WriteJson(new ScrobbleResponse(string.Format("LFM{0}: {1}", resp.error, resp.message))); return; } }