Beispiel #1
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);
            }
        }
Beispiel #2
0
        public static async Task <string> Upload(string _fileName, string _path, ModelGoogleDrive _googleDrive, string _folderId)
        {
            try
            {
                Google.Apis.Drive.v3.Data.File response = new Google.Apis.Drive.v3.Data.File();

                using (var service = CallManager.InitGDriveService(_googleDrive))
                {
                    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(_googleDrive, _fileName);

                    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 (TaskCanceledException ex)
            {
                if (ex.CancellationToken.IsCancellationRequested)
                {
                    return("ERRO: CancellationToken is True.");
                }

                return("ERRO CancellationToken is False");
            }
            catch (Exception err)
            {
                HelperLogs.WriteLog(err.Message + "\br" + err.StackTrace);
                return("ERRO: " + err.Message);
            }
        }