Example #1
0
		/// <summary>
		/// Present the Last.fm authentication UI and attempt to obtain a session key.
		/// </summary>
		/// <param name="authView">A WebView to display the Last.fm authentication page.</param>
		/// <param name="onSuccess">A callback for when the authentication is successful.</param>
		/// <param name="onFailure">A callback for when the authentication fails.</param>
		/// <returns>An async Task.</returns>
		public async Task LastFmLogin(Windows.UI.Xaml.Controls.WebView authView, Func<bool> onSuccess, Func<bool> onFailure)
		{
			Contract.Requires(authView != null);
			Contract.Requires(onSuccess != null);
			Contract.Requires(onFailure != null);

			try
			{
				HttpResponseMessage getTokenMessage = await __client.GetAsync(LastFmApiSecrets.LASTFMAPI_GET_TOKEN);
				string tokenResponse = await getTokenMessage.Content.ReadAsStringAsync();

				string token = JsonObject
					.Parse(tokenResponse)
					.GetNamedString("token");

				string authUri = string.Format(LastFmApiSecrets.LASTFMAPI_AUTH_URL_FORMAT, token);
				authView.LoadCompleted += async (sender, e) =>
				{
					try
					{
						if (e.Uri.LocalPath.ToString().ToLowerInvariant() == LastFmApiSecrets.LASTFMAPI_AUTH_SUCCESS_URL)
						{
							string getSessionSignature = string.Format(LastFmApiSecrets.LASTFMAPI_GET_SESSION_SIGN_FORMAT, token);
							string getSessionSignatureMd5 = getSessionSignature.GetMd5Hash();
							string getSession = string.Format(LastFmApiSecrets.LASTFMAPI_GET_SESSION_FORMAT, token, getSessionSignatureMd5);
							HttpResponseMessage getSessionMessage = await __client.GetAsync(getSession);
							string sessionResponse = await getSessionMessage.Content.ReadAsStringAsync();

							JsonObject session = JsonObject
								.Parse(sessionResponse)
								.GetNamedObject("session");

							LogIn(session.GetNamedString("name"), session.GetNamedString("key"));

							onSuccess();
						}
					}
					catch (Exception)
					{
						// Failure after user interaction
						onFailure();
					}
				};
				authView.NavigationFailed += (sender, e) =>
				{
					// WebView navigation failure
					onFailure();
				};
				authView.Navigate(new Uri(authUri));
			}
			catch (Exception)
			{
				// Failure before user interaction
				onFailure();
			}
		}