/// <summary> /// Asynchronously gets a mapped API file. /// </summary> /// <param name="result">The result.</param> /// <param name="response">The response.</param> /// <returns></returns> protected static async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > GetMappedAPIFileAsync( SerializableAPIResult <CloudStorageServiceAPIFile> result, Stream response) { if (response == null) { return(null); } string content; using (StreamReader reader = new StreamReader(Util.ZlibUncompress(response))) content = await reader.ReadToEndAsync(); if (String.IsNullOrWhiteSpace(content)) { result.Error = new SerializableAPIError { ErrorMessage = @"The settings file was not in a correct format." }; return(result); } result.Result = new CloudStorageServiceAPIFile { FileName = $"{SettingsFileNameWithoutExtension}.xml", FileContent = content }; return(result); }
/// <summary> /// Requests the Google calendar authentication. /// </summary> /// <param name="checkAuth">if set to <c>true</c> [check authentication].</param> private async Task RequestGoogleCalendarAuthentication(bool checkAuth = false) { if (!Enabled || !rbGoogle.Checked) { return; } apiResponseLabel.ResetText(); apiResponseLabel.ResetForeColor(); if (checkAuth && !GoogleCalendarEvent.HasCredentialsStored()) { return; } throbber.State = ThrobberState.Rotating; throbber.Visible = true; SerializableAPIResult <SerializableAPICredentials> result = await GoogleCalendarEvent.RequestAuth(checkAuth); throbber.State = ThrobberState.Stopped; throbber.Visible = false; btnRequestAuth.Enabled = result.HasError; btnRevokeAuth.Enabled = tbGoogleCalendarName.Enabled = cbGoogleReminder.Enabled = !result.HasError; apiResponseLabel.ForeColor = result.HasError ? Color.Red : Color.Green; apiResponseLabel.Text = result.HasError ? result.Error.ErrorCode ?? result.Error.ErrorMessage : @"Authenticated"; }
/// <summary> /// Downloads the settings file asynchronously. /// </summary> public async Task DownloadSettingsFileAsync() { if (m_queryPending) { return; } m_queryPending = true; EveMonClient.Trace("Initiated"); SerializableAPIResult <CloudStorageServiceAPIFile> result = await DownloadFileAsync().ConfigureAwait(false); FileDownloaded?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); m_queryPending = false; string resultText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace($"CloudStorageServiceProvider.DownloadSettingsFileAsync - {resultText}", printMethod: false); if (!result.HasError) { Dispatcher.Invoke(() => SaveSettingsFile(result.Result)); } }
/// <summary> /// Asynchronously checks the provider authentication code. /// </summary> /// <param name="code">The code.</param> /// <returns></returns> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckProviderAuthCodeAsync( string code) { if (m_result == null) { m_result = new SerializableAPIResult <SerializableAPICredentials>(); } try { // Checks that the client is authenticated // Settings save is done on caller method return(await CheckAuthAsync().ConfigureAwait(false)); } catch (OneDriveException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Asynchronously checks the authentication code. /// </summary> /// <param name="code">The code.</param> public async Task CheckAuthCodeAsync(string code) { if (m_queryPending && AuthSteps == AuthenticationSteps.Two) { return; } m_queryPending = true; EveMonClient.Trace("Initiated"); SerializableAPIResult <SerializableAPICredentials> result = await CheckProviderAuthCodeAsync(code).ConfigureAwait(false); if (!result.HasError) { Settings.Save(); } IsAuthenticated = !result.HasError && HasCredentialsStored; CredentialsChecked?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); m_queryPending = false; var actionText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace($"CloudStorageServiceProvider.CheckAuthCodeAsync - {actionText}", printMethod: false); }
/// <summary> /// Asynchronously checks the API authentication with credentials is valid. /// </summary> /// <param name="userID">The user identifier.</param> /// <param name="apiKey">The API key.</param> public async Task CheckAPIAuthWithCredentialsIsValidAsync(uint userID, string apiKey) { if (m_queryPending) { return; } m_queryPending = true; EveMonClient.Trace("Initiated"); IsAuthenticated = false; SerializableAPIResult <SerializableAPICredentials> result = await CheckProviderAuthWithCredentialsIsValidAsync(userID, apiKey).ConfigureAwait(false); IsAuthenticated = !result.HasError; CredentialsChecked?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); m_queryPending = false; var resultText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace($"CloudStorageServiceProvider.CheckAPIAuthWithCredentialsIsValidAsync - {resultText}", printMethod: false); }
/// <summary> /// Asynchronously requests the provider an authentication code. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > RequestProviderAuthCodeAsync() { m_result = new SerializableAPIResult <SerializableAPICredentials>(); await CheckAuthCodeAsync(String.Empty).ConfigureAwait(false); return(m_result); }
/// <summary> /// Logon to Google. /// </summary> /// <param name="checkAuth">if set to <c>true</c> [check authentication].</param> /// <returns></returns> private static async Task <SerializableAPIResult <SerializableAPICredentials> > LogOn(bool checkAuth = false) { SerializableAPIResult <SerializableAPICredentials> result = new SerializableAPIResult <SerializableAPICredentials>(); if (checkAuth && !HasCredentialsStored()) { return(result); } var clientSecrets = new ClientSecrets { ClientId = Util.Decrypt(GoogleDriveCloudStorageServiceSettings.Default.AppKey, CultureConstants.InvariantCulture.NativeName), ClientSecret = Util.Decrypt(GoogleDriveCloudStorageServiceSettings.Default.AppSecret, CultureConstants.InvariantCulture.NativeName) }; try { s_credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, new[] { CalendarService.Scope.Calendar }, UserId, CancellationToken.None, new FileDataStore(GetCredentialsPath(checkAuth), true)); if (checkAuth) { using (CalendarService client = await GetClient()) await client.Settings.List().ExecuteAsync(); } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (APIException exc) { result.Error = new SerializableAPIError { ErrorCode = exc.ErrorCode, ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
/// <summary> /// Asynchronously checks the authentication. /// </summary> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckAuthenticationAsync() { if (m_result == null) { m_result = new SerializableAPIResult <SerializableAPICredentials>(); } if (!HasCredentialsStored) { return(m_result); } try { InitializeCertPinning(); using (DropboxClient client = GetClient()) { await client.Users.GetCurrentAccountAsync().ConfigureAwait(false); } } catch (ApiException <GetAccountError> exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (AuthException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; if (exc.ErrorResponse.IsInvalidAccessToken && HasCredentialsStored) { await ResetSettingsAsync().ConfigureAwait(false); } } catch (BadInputException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } finally { ClearCertPinning(); } return(m_result); }
/// <summary> /// Asynchronously checks the authentication. /// </summary> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckAuthenticationAsync() { if (m_result == null) { m_result = new SerializableAPIResult <SerializableAPICredentials>(); } try { if (!HasCredentialsStored) { return(m_result); } if (s_credential == null) { await GetCredentialsAsync().ConfigureAwait(false); } using (DriveService client = GetClient()) { AboutResource.GetRequest request = client.About.Get(); request.Fields = "user"; await request.ExecuteAsync().ConfigureAwait(false); } } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; if (HasCredentialsStored) { await ResetSettingsAsync().ConfigureAwait(false); } } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> /// <exception cref="System.IO.FileNotFoundException"></exception> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > DownloadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); if (string.IsNullOrWhiteSpace(m_fileId)) { throw new FileNotFoundException(); } using (DriveService client = GetClient()) using (Stream stream = new MemoryStream()) { FilesResource.GetRequest request = client.Files.Get(m_fileId); request.Fields = "id, name"; IDownloadProgress response = await request.DownloadAsync(stream).ConfigureAwait(false); if (response.Exception == null) { return(await GetMappedAPIFileAsync(result, stream)); } result.Error = new SerializableAPIError { ErrorMessage = response.Exception.Message }; } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > UploadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); CommitInfo commitInfo = new CommitInfo($"/{SettingsFileNameWithoutExtension}", WriteMode.Overwrite.Instance); InitializeCertPinning(); using (DropboxClient client = GetClient()) using (Stream stream = Util.GetMemoryStream(content)) { await client.Files.UploadAsync(commitInfo, stream).ConfigureAwait(false); return(result); } } catch (ApiException <UploadError> ex) { result.Error = new SerializableAPIError { ErrorMessage = ex.Message }; } catch (AuthException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (BadInputException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } finally { ClearCertPinning(); } return(result); }
/// <summary> /// Uploads the settings file. /// </summary> /// <returns></returns> public async Task <bool> UploadSettingsFileOnExitAsync() { if (!CloudStorageServiceSettings.Default.UploadAlways || !HasCredentialsStored) { return(true); } //var isValid = CheckAPIAuthIsValid(); // Quit if user is not authenticated if (!IsAuthenticated && !CheckAPIAuthIsValid()) { MessageBox.Show($"The {Name} API credentials could not be authenticated.", $"{Name} API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } EveMonClient.Trace("Initiated"); // Ask for user action if uploading fails while (true) { SerializableAPIResult <CloudStorageServiceAPIFile> result = await UploadFileAsync().ConfigureAwait(false); FileUploaded?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); if (!result.HasError) { EveMonClient.Trace("CloudStorageServiceProvider.UploadSettingsFileOnExitAsync - Completed", printMethod: false); return(true); } DialogResult dialogResult = MessageBox.Show(result.Error?.ErrorMessage, $"{Name} API Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); switch (dialogResult) { case DialogResult.Abort: EveMonClient.Trace("Failed and Aborted"); return(false); case DialogResult.Retry: continue; } EveMonClient.Trace("Failed and Ignored"); return(true); } }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > DownloadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { InitializeCertPinning(); DownloadArg arg = new DownloadArg($"/{SettingsFileNameWithoutExtension}"); using (DropboxClient client = GetClient()) { Task <Stream> response = await client.Files.DownloadAsync(arg) .ContinueWith(async task => await task.Result.GetContentAsStreamAsync()); return(await GetMappedAPIFileAsync(result, response.Result)); } } catch (ApiException <DownloadError> ex) { result.Error = new SerializableAPIError { ErrorMessage = ex.Message }; } catch (AuthException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (BadInputException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } finally { ClearCertPinning(); } return(result); }
/// <summary> /// Downloads the settings file. /// </summary> /// <returns></returns> public CloudStorageServiceAPIFile DownloadSettingsFile() { if (!CloudStorageServiceSettings.Default.DownloadAlways || !HasCredentialsStored) { return(null); } if (!IsAuthenticated && !CheckAPIAuthIsValid()) { MessageBox.Show($"The {Name} API credentials could not be authenticated.", $"{Name} API Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } EveMonClient.Trace("Initiated"); SerializableAPIResult <CloudStorageServiceAPIFile> result = DownloadFileAsync().Result; FileDownloaded?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); if (CloudStorageServiceSettings.Default.UseImmediately) { if (result.HasError) { MessageBox.Show($"File could not be downloaded.\n\nThe error was:\n{result.Error?.ErrorMessage}", $"{Name} API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { EveMonClient.Trace("Completed"); return(result.Result); } } else { var resultText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace(resultText); if (!result.HasError) { SaveSettingsFile(result.Result); } } return(null); }
/// <summary> /// Asynchronously resets the settings. /// </summary> public async Task ResetSettingsAsync() { EveMonClient.Trace("Initiated"); SerializableAPIResult <SerializableAPICredentials> result = await RevokeAuthorizationAsync().ConfigureAwait(false); if (!result.HasError) { Settings.Reset(); } SettingsReset?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(null)); var resultText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace($"CloudStorageServiceProvider.ResetSettingsAsync - {resultText}", printMethod: false); }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > UploadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); using (OneDriveClient client = (OneDriveClient)await GetClient().ConfigureAwait(false)) using (Stream stream = Util.GetMemoryStream(content)) { Item response = await(String.IsNullOrWhiteSpace(m_fileId) ? client.Drive.Special.AppRoot .ItemWithPath(Uri.EscapeUriString(SettingsFileNameWithoutExtension)) : client.Drive.Items[m_fileId]) .Content.Request().PutAsync <Item>(stream).ConfigureAwait(false); m_fileId = response?.Id; } } catch (OneDriveException exc) { if (exc.Error.Code == OneDriveErrorCode.AuthenticationFailure.ToString()) { IsAuthenticated = false; } result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
/// <summary> /// Asynchronously requests the provider an authentication code. /// </summary> protected override Task <SerializableAPIResult <SerializableAPICredentials> > RequestProviderAuthCodeAsync() { m_result = new SerializableAPIResult <SerializableAPICredentials>(); try { Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri( Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppKey, CultureConstants.InvariantCulture.NativeName)); Util.OpenURL(authorizeUri); } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(Task.FromResult(m_result)); }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> /// <exception cref="System.IO.FileNotFoundException"></exception> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > DownloadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); if (String.IsNullOrWhiteSpace(m_fileId)) { throw new FileNotFoundException(); } using (OneDriveClient client = (OneDriveClient)await GetClient().ConfigureAwait(false)) { Stream stream = await client.Drive.Items[m_fileId].Content.Request().GetAsync().ConfigureAwait(false); return(await GetMappedAPIFileAsync(result, stream)); } } catch (OneDriveException exc) { if (exc.Error.Code == OneDriveErrorCode.AuthenticationFailure.ToString()) { IsAuthenticated = false; } result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
/// <summary> /// Asynchronously checks the provider authentication code. /// </summary> /// <param name="code">The code.</param> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckProviderAuthCodeAsync( string code) { if (m_result == null) { m_result = new SerializableAPIResult <SerializableAPICredentials>(); } try { OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppKey, CultureConstants.InvariantCulture.NativeName), Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppSecret, CultureConstants.InvariantCulture.NativeName)).ConfigureAwait(false); await CheckAuthenticationAsync().ConfigureAwait(false); if (!m_result.HasError) { DropboxCloudStorageServiceSettings.Default.AccessToken = response.AccessToken; } } catch (OAuth2Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Asynchronously checks the authentication. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > CheckAuthenticationAsync() { if (m_result == null) { m_result = new SerializableAPIResult <SerializableAPICredentials>(); } try { if (!HasCredentialsStored) { return(m_result); } // Checks that the client is authenticated // Settings save is done on called method return(await CheckAuthAsync(saveOnChangeCheck : true).ConfigureAwait(false)); } catch (OneDriveException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; if (exc.Error.Code == OneDriveErrorCode.AuthenticationFailure.ToString() && HasCredentialsStored) { await ResetSettingsAsync().ConfigureAwait(false); } } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Asynchronously checks the authentication. /// </summary> /// <param name="saveOnChangeCheck">if set to <c>true</c> save the settings on change check.</param> /// <returns></returns> private async Task <SerializableAPIResult <SerializableAPICredentials> > CheckAuthAsync(bool saveOnChangeCheck = false) { SerializableAPIResult <SerializableAPICredentials> result = new SerializableAPIResult <SerializableAPICredentials>(); using (OneDriveClient client = (OneDriveClient)await GetClient()) { if (!client.IsAuthenticated) { result.Error = new SerializableAPIError { ErrorMessage = "The client could not be authenticated" }; return(result); } AuthenticationProvider authenticationProvider = (MicrosoftAccountAuthenticationProvider)client.AuthenticationProvider; if (authenticationProvider.CurrentAccountSession.RefreshToken == OneDriveCloudStorageServiceSettings.Default.RefreshToken) { return(result); } OneDriveCloudStorageServiceSettings.Default.Credentials = Encoding.Default.GetString(authenticationProvider.ServiceInfo.CredentialCache.GetCacheBlob()); OneDriveCloudStorageServiceSettings.Default.UserId = authenticationProvider.CurrentAccountSession.UserId; OneDriveCloudStorageServiceSettings.Default.RefreshToken = authenticationProvider.CurrentAccountSession.RefreshToken; if (saveOnChangeCheck) { Settings.Save(); } } return(result); }
/// <summary> /// Logout from Google. /// </summary> private static async Task <SerializableAPIResult <SerializableAPICredentials> > LogOut() { SerializableAPIResult <SerializableAPICredentials> result = new SerializableAPIResult <SerializableAPICredentials>(); try { Task <bool> revokeTokenAsync = s_credential?.RevokeTokenAsync(CancellationToken.None); bool success = revokeTokenAsync != null && await revokeTokenAsync; if (!success) { result.Error = new SerializableAPIError { ErrorMessage = "Unable to revoke authorization" }; } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
/// <summary> /// Asynchronously requests an authentication code. /// </summary> public async Task RequestAuthCodeAsync() { if (m_queryPending || HasCredentialsStored) { return; } m_queryPending = true; EveMonClient.Trace("Initiated"); IsAuthenticated = false; SerializableAPIResult <SerializableAPICredentials> result = await RequestProviderAuthCodeAsync().ConfigureAwait(false); CredentialsChecked?.ThreadSafeInvoke(this, new CloudStorageServiceProviderEventArgs(result.Error?.ErrorMessage)); m_queryPending = false; var resultText = result.HasError ? "Failed" : "Completed"; EveMonClient.Trace($"CloudStorageServiceProvider.RequestAuthCodeAsync - {resultText}", printMethod: false); }
/// <summary> /// Asynchronously revokes the authorization. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > RevokeAuthorizationAsync() { m_result = new SerializableAPIResult <SerializableAPICredentials>(); try { using (OneDriveClient client = (OneDriveClient)await GetClient().ConfigureAwait(false)) { bool cansignout = client.AuthenticationProvider.CurrentAccountSession.CanSignOut; if (cansignout) { await client.AuthenticationProvider.SignOutAsync().ConfigureAwait(false); } else { m_result.Error = new SerializableAPIError { ErrorMessage = "Unable to revoke authorization" } }; } } catch (OneDriveException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Asynchronously revokes the authorization. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > RevokeAuthorizationAsync() { m_result = new SerializableAPIResult <SerializableAPICredentials>(); try { Task <bool> revokeTokenAsync = s_credential?.RevokeTokenAsync(CancellationToken.None); bool success = revokeTokenAsync != null && await revokeTokenAsync.ConfigureAwait(false); if (!success) { m_result.Error = new SerializableAPIError { ErrorMessage = "Unable to revoke authorization" }; } } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Handles the Click event of the btnRevokeAuth control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private async void btnRevokeAuth_Click(object sender, EventArgs e) { apiResponseLabel.ResetText(); apiResponseLabel.ResetForeColor(); throbber.State = ThrobberState.Rotating; throbber.Visible = true; SerializableAPIResult <SerializableAPICredentials> result = await GoogleCalendarEvent.RevokeAuth(); throbber.State = ThrobberState.Stopped; throbber.Visible = false; btnRequestAuth.Enabled = !result.HasError; btnRevokeAuth.Enabled = tbGoogleCalendarName.Enabled = cbGoogleReminder.Enabled = result.HasError; if (!result.HasError) { return; } apiResponseLabel.ForeColor = Color.Red; apiResponseLabel.Text = result.Error.ErrorMessage; }
/// <summary> /// Asynchronously requests the provider an authentication code. /// </summary> protected override async Task <SerializableAPIResult <SerializableAPICredentials> > RequestProviderAuthCodeAsync() { m_result = new SerializableAPIResult <SerializableAPICredentials>(); try { await GetCredentialsAsync().ConfigureAwait(false); await CheckAuthCodeAsync(string.Empty).ConfigureAwait(false); } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (APIException exc) { m_result.Error = new SerializableAPIError { ErrorCode = exc.ErrorCode, ErrorMessage = exc.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(m_result); }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> UploadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); using (OneDriveClient client = (OneDriveClient)await GetClient().ConfigureAwait(false)) using (Stream stream = Util.GetMemoryStream(content)) { Item response = await (String.IsNullOrWhiteSpace(m_fileId) ? client.Drive.Special.AppRoot .ItemWithPath(Uri.EscapeUriString(SettingsFileNameWithoutExtension)) : client.Drive.Items[m_fileId]) .Content.Request().PutAsync<Item>(stream).ConfigureAwait(false); m_fileId = response?.Id; } } catch (OneDriveException exc) { if (exc.Error.Code == OneDriveErrorCode.AuthenticationFailure.ToString()) IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously checks the authentication. /// </summary> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> CheckAuthenticationAsync() { if (m_result == null) m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { if (!HasCredentialsStored) return m_result; using (DropboxClient client = GetClient()) { await client.Users.GetCurrentAccountAsync().ConfigureAwait(false); } } catch (ApiException<GetAccountError> exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (AuthException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; if (exc.ErrorResponse.IsInvalidAccessToken && HasCredentialsStored) await ResetSettingsAsync().ConfigureAwait(false); } catch (BadInputException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> DownloadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { DownloadArg arg = new DownloadArg($"/{SettingsFileNameWithoutExtension}"); using (DropboxClient client = GetClient()) { Task<Stream> response = await client.Files.DownloadAsync(arg) .ContinueWith(async task => await task.Result.GetContentAsStreamAsync()); return await GetMappedAPIFileAsync(result, response.Result); } } catch (ApiException<DownloadError> ex) { result.Error = new SerializableAPIError { ErrorMessage = ex.Message }; } catch (AuthException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (BadInputException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> UploadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); CommitInfo commitInfo = new CommitInfo($"/{SettingsFileNameWithoutExtension}", WriteMode.Overwrite.Instance); using (DropboxClient client = GetClient()) using (Stream stream = Util.GetMemoryStream(content)) { await client.Files.UploadAsync(commitInfo, stream).ConfigureAwait(false); return result; } } catch (ApiException<UploadError> ex) { result.Error = new SerializableAPIError { ErrorMessage = ex.Message }; } catch (AuthException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (BadInputException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Logout from Google. /// </summary> private static async Task<SerializableAPIResult<SerializableAPICredentials>> LogOut() { SerializableAPIResult<SerializableAPICredentials> result = new SerializableAPIResult<SerializableAPICredentials>(); try { Task<bool> revokeTokenAsync = s_credential?.RevokeTokenAsync(CancellationToken.None); bool success = revokeTokenAsync != null && await revokeTokenAsync; if (!success) { result.Error = new SerializableAPIError { ErrorMessage = "Unable to revoke authorization" }; } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously requests the provider an authentication code. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> RequestProviderAuthCodeAsync() { m_result = new SerializableAPIResult<SerializableAPICredentials>(); await CheckAuthCodeAsync(String.Empty).ConfigureAwait(false); return m_result; }
/// <summary> /// Asynchronously requests the provider an authentication code. /// </summary> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> RequestProviderAuthCodeAsync() { m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { await GetCredentialsAsync().ConfigureAwait(false); await CheckAuthCodeAsync(String.Empty).ConfigureAwait(false); } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (APIException exc) { m_result.Error = new SerializableAPIError { ErrorCode = exc.ErrorCode, ErrorMessage = exc.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> /// <exception cref="System.IO.FileNotFoundException"></exception> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> DownloadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); if (String.IsNullOrWhiteSpace(m_fileId)) throw new FileNotFoundException(); using (DriveService client = GetClient()) using (Stream stream = new MemoryStream()) { FilesResource.GetRequest request = client.Files.Get(m_fileId); request.Fields = "id, name"; IDownloadProgress response = await request.DownloadAsync(stream).ConfigureAwait(false); if (response.Exception == null) return await GetMappedAPIFileAsync(result, stream); result.Error = new SerializableAPIError { ErrorMessage = response.Exception.Message }; } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously checks the authentication. /// </summary> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> CheckAuthenticationAsync() { if (m_result == null) m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { if (!HasCredentialsStored) return m_result; if (s_credential == null) await GetCredentialsAsync().ConfigureAwait(false); using (DriveService client = GetClient()) { AboutResource.GetRequest request = client.About.Get(); request.Fields = "user"; await request.ExecuteAsync().ConfigureAwait(false); } } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; if (HasCredentialsStored) await ResetSettingsAsync().ConfigureAwait(false); } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > UploadFileAsync() { SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); using (DriveService client = GetClient()) using (Stream stream = Util.GetMemoryStream(content)) { ResumableUpload <GoogleFile, GoogleFile> request; GoogleFile fileMetadata = new GoogleFile { Name = SettingsFileNameWithoutExtension }; if (string.IsNullOrWhiteSpace(m_fileId)) { //Upload fileMetadata.Parents = new List <string> { Spaces }; request = client.Files.Create(fileMetadata, stream, ContentType); ((FilesResource.CreateMediaUpload)request).Fields = "id, name"; } else { //Update request = client.Files.Update(fileMetadata, m_fileId, stream, ContentType); ((FilesResource.UpdateMediaUpload)request).AddParents = Spaces; ((FilesResource.UpdateMediaUpload)request).Fields = "id, name"; } // Do the actual upload IUploadProgress response = await request.UploadAsync().ConfigureAwait(false); m_fileId = request.ResponseBody?.Id; // Chceck response for exception if (response.Exception != null) { result.Error = new SerializableAPIError { ErrorMessage = response.Exception.Message }; } } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return(result); }
/// <summary> /// Asynchronously checks the provider authentication code. /// </summary> /// <param name="code">The code.</param> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> CheckProviderAuthCodeAsync( string code) { if (m_result == null) m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { OAuth2Response response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(code, Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppKey, CultureConstants.InvariantCulture.NativeName), Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppSecret, CultureConstants.InvariantCulture.NativeName)).ConfigureAwait(false); await CheckAuthenticationAsync().ConfigureAwait(false); if (!m_result.HasError) DropboxCloudStorageServiceSettings.Default.AccessToken = response.AccessToken; } catch (OAuth2Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously checks the authentication. /// </summary> /// <param name="saveOnChangeCheck">if set to <c>true</c> save the settings on change check.</param> /// <returns></returns> private async Task<SerializableAPIResult<SerializableAPICredentials>> CheckAuthAsync(bool saveOnChangeCheck = false) { SerializableAPIResult<SerializableAPICredentials> result = new SerializableAPIResult<SerializableAPICredentials>(); using (OneDriveClient client = (OneDriveClient)await GetClient()) { if (!client.IsAuthenticated) { result.Error = new SerializableAPIError { ErrorMessage = "The client could not be authenticated" }; return result; } AuthenticationProvider authenticationProvider = (MicrosoftAccountAuthenticationProvider)client.AuthenticationProvider; if (authenticationProvider.CurrentAccountSession.RefreshToken == OneDriveCloudStorageServiceSettings.Default.RefreshToken) { return result; } OneDriveCloudStorageServiceSettings.Default.Credentials = Encoding.Default.GetString(authenticationProvider.ServiceInfo.CredentialCache.GetCacheBlob()); OneDriveCloudStorageServiceSettings.Default.UserId = authenticationProvider.CurrentAccountSession.UserId; OneDriveCloudStorageServiceSettings.Default.RefreshToken = authenticationProvider.CurrentAccountSession.RefreshToken; if (saveOnChangeCheck) Settings.Save(); } return result; }
/// <summary> /// Asynchronously checks the authentication. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> CheckAuthenticationAsync() { if (m_result == null) m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { if (!HasCredentialsStored) return m_result; // Checks that the client is authenticated // Settings save is done on called method return await CheckAuthAsync(saveOnChangeCheck: true).ConfigureAwait(false); } catch (OneDriveException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; if (exc.Error.Code == OneDriveErrorCode.AuthenticationFailure.ToString() && HasCredentialsStored) await ResetSettingsAsync().ConfigureAwait(false); } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously revokes the authorization. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> RevokeAuthorizationAsync() { m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { using (OneDriveClient client = (OneDriveClient)await GetClient().ConfigureAwait(false)) { bool cansignout = client.AuthenticationProvider.CurrentAccountSession.CanSignOut; if (cansignout) await client.AuthenticationProvider.SignOutAsync().ConfigureAwait(false); else m_result.Error = new SerializableAPIError { ErrorMessage = "Unable to revoke authorization" }; } } catch (OneDriveException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Logon to Google. /// </summary> /// <param name="checkAuth">if set to <c>true</c> [check authentication].</param> /// <returns></returns> private static async Task<SerializableAPIResult<SerializableAPICredentials>> LogOn(bool checkAuth = false) { SerializableAPIResult<SerializableAPICredentials> result = new SerializableAPIResult<SerializableAPICredentials>(); if (checkAuth && !HasCredentialsStored()) return result; var clientSecrets = new ClientSecrets { ClientId = Util.Decrypt(GoogleDriveCloudStorageServiceSettings.Default.AppKey, CultureConstants.InvariantCulture.NativeName), ClientSecret = Util.Decrypt(GoogleDriveCloudStorageServiceSettings.Default.AppSecret, CultureConstants.InvariantCulture.NativeName) }; try { s_credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, new[] { CalendarService.Scope.Calendar }, UserId, CancellationToken.None, new FileDataStore(GetCredentialsPath(checkAuth), true)); if (checkAuth) { using (CalendarService client = await GetClient()) await client.Settings.List().ExecuteAsync(); } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (APIException exc) { result.Error = new SerializableAPIError { ErrorCode = exc.ErrorCode, ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously downloads the file. /// </summary> /// <returns></returns> /// <exception cref="System.IO.FileNotFoundException"></exception> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> DownloadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); if (String.IsNullOrWhiteSpace(m_fileId)) throw new FileNotFoundException(); using (OneDriveClient client = (OneDriveClient)await GetClient().ConfigureAwait(false)) { Stream stream = await client.Drive.Items[m_fileId].Content.Request().GetAsync().ConfigureAwait(false); return await GetMappedAPIFileAsync(result, stream); } } catch (OneDriveException exc) { if (exc.Error.Code == OneDriveErrorCode.AuthenticationFailure.ToString()) IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously gets a mapped API file. /// </summary> /// <param name="result">The result.</param> /// <param name="response">The response.</param> /// <returns></returns> protected static async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> GetMappedAPIFileAsync( SerializableAPIResult<CloudStorageServiceAPIFile> result, Stream response) { if (response == null) return null; string content; using (StreamReader reader = new StreamReader(Util.ZlibUncompress(response))) content = await reader.ReadToEndAsync(); if (String.IsNullOrWhiteSpace(content)) { result.Error = new SerializableAPIError { ErrorMessage = @"The settings file was not in a correct format." }; return result; } result.Result = new CloudStorageServiceAPIFile { FileName = $"{SettingsFileNameWithoutExtension}.xml", FileContent = content }; return result; }
/// <summary> /// Asynchronously revokes the authorization. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> RevokeAuthorizationAsync() { m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { Task<bool> revokeTokenAsync = s_credential?.RevokeTokenAsync(CancellationToken.None); bool success = revokeTokenAsync != null && await revokeTokenAsync.ConfigureAwait(false); if (!success) { m_result.Error = new SerializableAPIError { ErrorMessage = "Unable to revoke authorization" }; } } catch (GoogleApiException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously checks the provider authentication code. /// </summary> /// <param name="code">The code.</param> /// <returns></returns> protected override async Task<SerializableAPIResult<SerializableAPICredentials>> CheckProviderAuthCodeAsync( string code) { if (m_result == null) m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { // Checks that the client is authenticated // Settings save is done on caller method return await CheckAuthAsync().ConfigureAwait(false); } catch (OneDriveException exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return m_result; }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> UploadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false); byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); using (DriveService client = GetClient()) using (Stream stream = Util.GetMemoryStream(content)) { ResumableUpload<GoogleFile, GoogleFile> request; GoogleFile fileMetadata = new GoogleFile { Name = SettingsFileNameWithoutExtension }; if (String.IsNullOrWhiteSpace(m_fileId)) { //Upload fileMetadata.Parents = new List<string> { Spaces }; request = client.Files.Create(fileMetadata, stream, ContentType); ((FilesResource.CreateMediaUpload)request).Fields = "id, name"; } else { //Update request = client.Files.Update(fileMetadata, m_fileId, stream, ContentType); ((FilesResource.UpdateMediaUpload)request).AddParents = Spaces; ((FilesResource.UpdateMediaUpload)request).Fields = "id, name"; } // Do the actual upload IUploadProgress response = await request.UploadAsync().ConfigureAwait(false); m_fileId = request.ResponseBody?.Id; // Chceck response for exception if (response.Exception != null) { result.Error = new SerializableAPIError { ErrorMessage = response.Exception.Message }; } } } catch (GoogleApiException exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Error.Message }; } catch (TokenResponseException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
/// <summary> /// Asynchronously requests the provider an authentication code. /// </summary> protected override Task<SerializableAPIResult<SerializableAPICredentials>> RequestProviderAuthCodeAsync() { m_result = new SerializableAPIResult<SerializableAPICredentials>(); try { Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri( Util.Decrypt(DropboxCloudStorageServiceSettings.Default.AppKey, CultureConstants.InvariantCulture.NativeName)); Util.OpenURL(authorizeUri); } catch (Exception exc) { m_result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return Task.FromResult(m_result); }