using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using IF.Lastfm.Core.Api; using IF.Lastfm.Core.Api.Enums; using IF.Lastfm.Core.Api.Helpers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace IF.Lastfm.Core { public class LastFm : ILastFm { #region Constants public const string ApiRoot = "http://ws.audioscrobbler.com/2.0/"; private const string ApiRootFormat = "{0}://ws.audioscrobbler.com/2.0/?method={1}&api_key={2}{3}"; private const string ResponseFormat = "json"; public const int DefaultPageLength = 20; #endregion #region Api objects public IAuth Auth { get; set; } #endregion #region Api helper methods public static string FormatApiUrl(string method, string apikey, Dictionary parameters = null, bool secure = false) { if (parameters == null) { parameters = new Dictionary(); } parameters.Add("format", ResponseFormat); var querystring = LastFm.FormatQueryParameters(parameters.OrderBy(kv => kv.Key)); var protocol = secure ? "https" : "http"; return string.Format(ApiRootFormat, protocol, method, apikey, querystring); } public static FormUrlEncodedContent CreatePostBody(string method, string apikey, string apisig, IEnumerable> parameters) { var init = new Dictionary { {"method", method}, {"api_key", apikey}, {"api_sig", apisig}, {"format", ResponseFormat} }; var requestParameters = init.Concat(parameters); return new FormUrlEncodedContent(requestParameters); } public static string FormatQueryParameters(IEnumerable> parameters) { const string parameterFormat = "&{0}={1}"; var builder = new StringBuilder(); foreach (var pair in parameters) { builder.Append(string.Format(parameterFormat, pair.Key, pair.Value)); } return builder.ToString(); } public static bool IsResponseValid(string json, out LastFmApiError error) { if (!json.Contains("error")) { error = LastFmApiError.None; return true; } error = LastFmApiError.Unknown; JObject jo; try { jo = JsonConvert.DeserializeObject(json); } catch (JsonException) { return false; } var code = jo.Value("error"); switch (code) { case 2: error = LastFmApiError.ServiceServiceWhereArtThou; break; case 3: error = LastFmApiError.BadMethod; break; case 4: error = LastFmApiError.BadAuth; break; case 5: error = LastFmApiError.BadFormat; break; case 6: error = LastFmApiError.MissingParameters; break; case 7: error = LastFmApiError.BadResource; break; case 8: error = LastFmApiError.Failure; break; case 9: error = LastFmApiError.SessionExpired; break; case 10: error = LastFmApiError.BadApiKey; break; case 11: error = LastFmApiError.ServiceDown; break; case 13: error = LastFmApiError.BadMethodSignature; break; case 16: error = LastFmApiError.TemporaryFailure; break; case 26: error = LastFmApiError.KeySuspended; break; case 29: error = LastFmApiError.RateLimited; break; } return false; } #endregion } }