Example #1
0
        private long GetGoogleDriveSpaceAvailable()
        {
            long storageAvailable = -1;

            AboutResource.GetRequest getRequest = driveService.About.Get();
            getRequest.Fields = "*";
            About about = getRequest.Execute();

            long?storageLimit = about.StorageQuota.Limit;
            long?storageUsage = about.StorageQuota.Usage;



            if (!(storageLimit is null || storageUsage is null))
            {
                long storageLimitValue = (long)storageLimit;
                long storageUsageValue = (long)storageUsage;

                storageAvailable = storageLimitValue - storageUsageValue;
            }

            logger.LogDebug($"Google account space limit (bytes): {storageLimit}");
            logger.LogDebug($"Google account space used (bytes): {storageUsage}");
            logger.LogDebug($"Google account space available (bytes): {storageAvailable}");

            return(storageAvailable);
        }
Example #2
0
        public About getUserDriveInfo(DriveService service)
        {
            AboutResource.GetRequest getRequest = service.About.Get();
            getRequest.Fields = "*";
            var about = getRequest.Execute();

            return(about);
        }
Example #3
0
 private string[] GetUserDetails(DriveService service)
 {
     string[] details = new string[2];
     AboutResource.GetRequest request = service.About.Get();
     request.Fields = "user(emailAddress, displayName)";
     details.SetValue(request.Execute().User.EmailAddress, 0);
     details.SetValue(request.Execute().User.DisplayName, 1);
     return(details);
 }
        /// <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>
        ///     <inheritdoc cref="ICustomGDriveService" />
        /// </summary>
        public long GetQuotaTotal(DriveService service)
        {
            var ag = new AboutResource.GetRequest(service)
            {
                Fields = "user,storageQuota"
            };
            var response = ag.Execute();

            if (response.StorageQuota.Limit.HasValue)
            {
                return(response.StorageQuota.Limit.Value);
            }
            return(-1);
        }
Example #6
0
 public static AboutResource.GetRequest AsDrive(this AboutResource.GetRequest request)
 {
     request.Fields = "storageQuota,user";
     return(request);
 }
Example #7
0
        static AutoResetEvent AuthCompletedHandle; // перед запуском аутентификации нужно = new AutoResetEvent(false);

        // Параметры аутентификации платформ-специфичны. Поэтому перед началом работы нужно вызвать этот метод в проекте конкретной платформы.
        public static void InitAuthParameters(string clientId, string redirectUrl, string appName, Action actionToStartAuth)
        {
            // Сохраним эти переменные на случай, если нужно будет перелогиниться, т.е. создать новый Auth, т.е. снова вызвать InitAuthParameters().
            authActionToStart = actionToStartAuth;
            authClientId      = clientId;
            authRedirectUrl   = redirectUrl;
            authAppName       = appName;

            Auth = new OAuth2Authenticator(
                clientId,
                string.Empty,
                "https://www.googleapis.com/auth/drive",
                new Uri("https://accounts.google.com/o/oauth2/auth"),
                new Uri(redirectUrl),
                new Uri("https://accounts.google.com/o/oauth2/token"),
                isUsingNativeUI: true);

            Auth.Completed += async(sender, e) =>
            {
                //Debug.WriteLine("EVENT Auth.Completed()");
                AuthenticatorCompletedEventArgs args = e as AuthenticatorCompletedEventArgs;

                if (args.IsAuthenticated)
                {
                    GoogleAuthorizationCodeFlow googleFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
                    {
                        ClientSecrets = new ClientSecrets()
                        {
                            ClientId     = clientId,
                            ClientSecret = string.Empty,
                        },
                        Scopes = new string[] { "https://www.googleapis.com/auth/drive" }
                    });

                    var token = new TokenResponse {
                        AccessToken = args.Account.Properties["access_token"], RefreshToken = args.Account.Properties["refresh_token"]
                    };
                    var credential = new UserCredential(googleFlow, "user", token);
                    Service = new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = authAppName,
                    });

                    //Получим справочную информацию об аккаунте:
                    AboutResource.GetRequest aboutReq = Service.About.Get();
                    aboutReq.Fields = "user";
                    About about = await aboutReq.ExecuteAsync();

                    User user = about.User;
                    UserName  = user.DisplayName;
                    UserEmail = user.EmailAddress;
                }
                else
                {
                    DependencyService.Get <IToast>().ShortToast("Google Drive authentication canceled.");
                }

                AuthCompletedHandle.Set();
            };

            Auth.Error += (sender, e) =>
            {
                //Debug.WriteLine("EVENT Auth.Error ");
                AuthenticatorErrorEventArgs err = e as AuthenticatorErrorEventArgs;
                DependencyService.Get <IToast>().ShortToast("GD Auth: " + err.Message + ". " + err.Exception?.ToString());
                AuthCompletedHandle.Set();
            };
        }