public ServiceAccountCredential AuthenticateServiceAccount(string serviceAccountEmail)
        {
            try
            {
                string[] scopes = new string[] { DriveService.Scope.Drive };

                var certificate = new X509Certificate2(_credentialFileName, "notasecret", X509KeyStorageFlags.Exportable);

                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = scopes
                }.FromCertificate(certificate));

                //DriveService service = new DriveService(new BaseClientService.Initializer()
                //{
                //    HttpClientInitializer = credential,
                //    ApplicationName = "ServicesCeltaInfra"
                //});

                return(credential);
            }
            catch (Exception err)
            {
                HelperLogs.WriteLog(err.Message + "\br" + err.StackTrace);
                throw err;
            }
        }
Esempio n. 2
0
        private static Google.Apis.Drive.v3.DriveService InitGDriveServiceWhithKey(ModelGoogleDrive _googleDrive)
        {
            try
            {
                Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
                {
                    ApplicationName = "ServicesCeltaInfra",
                    ApiKey          = _googleDrive.ApiKey
                });

                return(service);
            }
            catch (Exception err)
            {
                HelperLogs.WriteLog(err.Message + "\br" + err.StackTrace);
                throw err;
            }
        }
Esempio n. 3
0
        //private static Security security = new Security("servicesceltainfra-6f1e21301fbe.p12");

        private static Google.Apis.Drive.v3.DriveService InitGDriveService(ModelGoogleDrive _googleDrive)
        {
            try
            {
                Security security = new Security(_googleDrive.CredentialFileName);

                var credential = security.AuthenticateServiceAccount(_googleDrive.GoogleDriveAccountMail);
                Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "ServicesCeltaInfra"
                });

                return(service);
            }
            catch (Exception err)
            {
                HelperLogs.WriteLog(err.Message + "\br" + err.StackTrace);
                throw err;
            }
        }
Esempio n. 4
0
        public async Task <string> Upload(string _fileName, string _path, string _folderId, UserCredential userCredential)
        {
            try
            {
                Google.Apis.Drive.v3.Data.File response = new Google.Apis.Drive.v3.Data.File();

                using (var service = InitGDriveComputer(userCredential))
                {
                    service.HttpClient.Timeout = TimeSpan.FromHours(4);
                    var fileToUpload = new Google.Apis.Drive.v3.Data.File()
                    {
                        Name     = _fileName,
                        MimeType = MimeTypesMap.GetMimeType(System.IO.Path.GetExtension(_path)),
                        Parents  = new List <string>
                        {
                            _folderId
                        }
                    };


                    // *** Aqui validar se é para Atualizar ou criar !!! ***
                    // 1 - Caso existe verificar se o mesmo id encontra no GDrive
                    var isNew = await FindInGoogleDrive(_folderId, _fileName, userCredential);

                    if (String.IsNullOrEmpty(isNew.DriveId))
                    {
                        using (var stream = new System.IO.FileStream(_path + _fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            var request = service.Files.Create(fileToUpload, stream, fileToUpload.MimeType);
                            var valid   = await request.UploadAsync();

                            if (valid.Status != Google.Apis.Upload.UploadStatus.Completed)
                            {
                                HelperLogs.WriteLog(DateTime.Now + "Resposta de Upload ainda nao completa.");

                                for (int i = 0; i < 3; i++)
                                {
                                    await Task.Delay(3000);

                                    if (valid.Status != Google.Apis.Upload.UploadStatus.Completed)
                                    {
                                        i = 3;
                                    }
                                }
                            }

                            response = request.ResponseBody;

                            // var _file = new Google.Apis.Drive.v3.Data.File();
                            //_file.Name = System.IO.Path.GetFileName(fullPath);
                            // _file.Id = request.ResponseBody.Id;

                            Google.Apis.Drive.v3.Data.File       file          = request.ResponseBody;
                            Google.Apis.Drive.v3.Data.Permission newPermission = new Google.Apis.Drive.v3.Data.Permission();
                            newPermission.EmailAddress = "*****@*****.**";
                            newPermission.Type         = "user";
                            newPermission.Role         = "writer";

                            Google.Apis.Drive.v3.PermissionsResource.CreateRequest insertRequest = service.Permissions.Create(newPermission, file.Id);
                            insertRequest.Execute();
                        }
                    }
                    else
                    {
                        using (var stream = new System.IO.FileStream(_path + _fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            var request = service.Files.Update(fileToUpload, isNew.Id, stream, fileToUpload.MimeType);
                            await request.UploadAsync();

                            response = request.ResponseBody;

                            var _file = new Google.Apis.Drive.v3.Data.File();
                            //_file.Name = System.IO.Path.GetFileName(fullPath);
                            _file.Id = request.ResponseBody.Id;

                            //Google.Apis.Drive.v3.Data.File file = request.ResponseBody;
                            Google.Apis.Drive.v3.Data.Permission newPermission = new Google.Apis.Drive.v3.Data.Permission();
                            newPermission.EmailAddress = "*****@*****.**";
                            newPermission.Type         = "user";
                            newPermission.Role         = "writer";

                            Google.Apis.Drive.v3.PermissionsResource.CreateRequest insertRequest = service.Permissions.Create(newPermission, _file.Id);
                            insertRequest.Execute();
                        }
                    }

                    service.Dispose();
                };

                if (response == null)
                {
                    return(String.Empty);
                }

                return(response.Id);
            }

            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                return("ERRO: " + err.Message);
            }
        }
Esempio n. 5
0
        public static async Task <string> Up(string _fileName, string _path, ModelGoogleDrive _googleDrive, string _folderId)
        {
            try
            {
                string postUri       = "https://www.googleapis.com/drive/v3/files?uploadType=resumable";
                var    responseToken = await CallManager.GetToken(_googleDrive);

                string _bearerToken = responseToken.Substring(17, 219);

                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _bearerToken);

                using (HttpRequestMessage requestMessage = new HttpRequestMessage()
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri(postUri)
                })
                {
                    using (var stream = new System.IO.FileStream(_path + _fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        var           length = stream.Length.ToString();
                        StreamContent sc     = new StreamContent(stream);
                        sc.Headers.Add("Content-Type", "application/json; charset=UTF-8");
                        sc.Headers.Add("Content-Length", length);

                        requestMessage.Content = sc;

                        var response = client.PostAsync(postUri, requestMessage.Content).Result;
                        return(response.Content.ToString());
                    }
                }
                //var request = new HttpRequestMessage()
                //{
                //    Method = HttpMethod.Post,
                //    RequestUri = new Uri(postUri)
                //};



                //using (var stream = new System.IO.FileStream(_path + _fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                //{
                //    var length = stream.Length.ToString();
                //    StreamContent sc = new StreamContent(stream);
                //    sc.Headers.Add("Content-Type", "application/octet-stream");
                //    sc.Headers.Add("Content-Length", length);

                //    request.Content = sc;

                //    var response = new HttpClient().SendAsync(request).Result;

                //    //using (var formData = new MultipartFormDataContent())
                //    //{
                //    //    formData.Add(sc);

                //    //    var response = client.PostAsync(postUri, formData).Result;

                //    //    return response.StatusCode.ToString();
                //    //}
                //    return await response.Content.ReadAsStringAsync();
                //}
            }
            catch (Exception err)
            {
                HelperLogs.WriteLog(err.Message + "\br" + err.StackTrace);
                return("ERRO: " + err.Message);
            }
        }
Esempio n. 6
0
        public static async Task <string> UploadFull(DriveService _service, string _fileName, string _path, string _folderId)
        {
            try
            {
                Google.Apis.Drive.v3.Data.File response = new Google.Apis.Drive.v3.Data.File();

                using (var service = _service)
                {
                    service.HttpClient.Timeout = TimeSpan.FromHours(4);
                    var fileToUpload = new Google.Apis.Drive.v3.Data.File()
                    {
                        Name     = _fileName,
                        MimeType = MimeTypesMap.GetMimeType(System.IO.Path.GetExtension(_path)),
                        Parents  = new List <string>
                        {
                            _folderId
                        }
                    };
                    service.HttpClient.Timeout = TimeSpan.FromHours(4);


                    // *** Aqui validar se é para Atualizar ou criar !!! ***
                    // 1 - Caso existe verificar se o mesmo id encontra no GDrive
                    var isNew = await FindInGoogleDriveFull(_fileName, _folderId, service);

                    if (String.IsNullOrEmpty(isNew.DriveId))
                    {
                        using (var stream = new System.IO.FileStream(_path + _fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            var request = service.Files.Create(fileToUpload, stream, fileToUpload.MimeType);
                            var valid   = await request.UploadAsync();

                            if (valid.Status != Google.Apis.Upload.UploadStatus.Completed)
                            {
                                HelperLogs.WriteLog(DateTime.Now + "Resposta de Upload ainda nao completa.");

                                for (int i = 0; i < 3; i++)
                                {
                                    await Task.Delay(3000);

                                    if (valid.Status != Google.Apis.Upload.UploadStatus.Completed)
                                    {
                                        i = 3;
                                    }
                                }
                            }

                            response = request.ResponseBody;
                        }
                    }
                    else
                    {
                        using (var stream = new System.IO.FileStream(_path + _fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            var request = service.Files.Update(fileToUpload, isNew.Id, stream, fileToUpload.MimeType);
                            await request.UploadAsync();

                            response = request.ResponseBody;

                            var _file = new Google.Apis.Drive.v3.Data.File();
                            //_file.Name = System.IO.Path.GetFileName(fullPath);
                            _file.Id = request.ResponseBody.Id;
                        }
                    }

                    service.Dispose();
                };

                if (response == null)
                {
                    return(String.Empty);
                }

                return(response.Id);
            }
            catch (Exception err)
            {
                return(err.Message);
            }
        }