Esempio n. 1
0
        public static List <GoogleDriveFiles> GetContainsInFolder(String folderId)
        {
            List <string> ChildList = new List <string>();

            Google.Apis.Drive.v2.DriveService ServiceV2          = GetService_v2();
            ChildrenResource.ListRequest      ChildrenIDsRequest = ServiceV2.Children.List(folderId);
            do
            {
                ChildList children = ChildrenIDsRequest.Execute();

                if (children.Items != null && children.Items.Count > 0)
                {
                    foreach (var file in children.Items)
                    {
                        ChildList.Add(file.Id);
                    }
                }
                ChildrenIDsRequest.PageToken = children.NextPageToken;
            } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));

            //Get All File List
            List <GoogleDriveFiles> AllFileList     = GetDriveFiles();
            List <GoogleDriveFiles> Filter_FileList = new List <GoogleDriveFiles>();

            foreach (string Id in ChildList)
            {
                Filter_FileList.Add(AllFileList.Where(x => x.Id == Id).FirstOrDefault());
            }
            return(Filter_FileList);
        }
Esempio n. 2
0
        public static Google.Apis.Drive.v2.DriveService GetService_v2()
        {
            UserCredential credential;
            var            CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");

            using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                String FilePath = Path.Combine(CSPath, "DriveServiceCredentials.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(FilePath, true)).Result;
            }

            //Create Drive API service.
            Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "GoogleDriveRestAPI-v2",
            });
            return(service);
        }
Esempio n. 3
0
        public static Google.Apis.Drive.v2.DriveService GetService_v2()
        {
            UserCredential credential;

            using (var stream = new FileStream(@"D:\GitRepo\OnlineMovie-master\credentials.json", FileMode.Open, FileAccess.Read))
            {
                String FolderPath = @"D:\GitRepo\OnlineMovie-master\";
                String FilePath   = Path.Combine(FolderPath, "DriveServiceCredentials.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(FilePath, true)).Result;
            }

            //Create Drive API service.
            Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "GoogleDriveRestAPI-v2",
            });

            return(service);
        }
Esempio n. 4
0
        public static Google.Apis.Drive.v2.DriveService GetService_v2()
        {
            string         path = HttpContext.Current.Server.MapPath("~/App_Data/");
            UserCredential credential;

            using (var stream = new FileStream(path + "credentials.json", FileMode.Open, FileAccess.Read))
            {
                String FolderPath = HttpContext.Current.Server.MapPath("~");
                //String FolderPath = @"D:\";
                String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(FilePath, true)).Result;
            }

            //Create Drive API service.
            Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "GoogleDriveRestAPI-v2",
            });
            //Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.

            //Service Account
            //string path = HttpContext.Current.Server.MapPath("~/App_Data/");
            //var keyFilePath = path + "Quickstart-7181e72973ec.p12";     // Downloaded from https://console.developers.google.com
            //var serviceAccountEmail = "*****@*****.**";  // found https://console.developers.google.com

            ////loading the Key file
            //var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            //var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            //{
            //    Scopes = Scopes
            //}.FromCertificate(certificate));
            //Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()
            //{
            //    HttpClientInitializer = credential,
            //    ApplicationName = "Quickstart",

            //});
            //
            return(service);
        }
 private static void RenameFile(String fileId, String newTitle)
 {
     try
     {
         Google.Apis.Drive.v2.DriveService service = GetService_v2();
         Google.Apis.Drive.v2.Data.File    file    = new Google.Apis.Drive.v2.Data.File();
         file.Title = newTitle;
         // Rename the file.
         Google.Apis.Drive.v2.FilesResource.PatchRequest request = service.Files.Patch(file, fileId);
         Google.Apis.Drive.v2.Data.File updatedFile = request.Execute();
         //return updatedFile;
     }
     catch (Exception e)
     {
         Console.WriteLine("An error occurred: " + e.Message);
         //return null;
     }
 }
Esempio n. 6
0
        private async Task checkLoginAsync()
        {
            if (_driveService == null)
            {
                _driveService = new Google.Apis.Drive.v2.DriveService(
                    new BaseClientService.Initializer()
                {
                    HttpClientInitializer = _credential,
                    ApplicationName       = "FileExplorer",
                    //ApiKey = clientId
                });
                _aboutInfo = await _driveService.About.Get().ExecuteAsync();

                Alias           = String.Format(_aliasMask, _aboutInfo.User.DisplayName);
                ModelCache      = new EntryModelCache <GoogleDriveItemModel>(m => m.UniqueId, () => Alias, true);
                MimeTypeManager = new GoogleMimeTypeManager(_aboutInfo);
            }
        }
Esempio n. 7
0
        public static List <GoogleDriveFiles> GetContainsInFolderCustom(String folderId)
        {
            List <string> ChildList = new List <string>();

            Google.Apis.Drive.v2.DriveService ServiceV2          = GetService_v2();
            ChildrenResource.ListRequest      ChildrenIDsRequest = ServiceV2.Children.List(folderId);

            // for getting only folders
            ChildrenIDsRequest.Q      = "mimeType!='application/vnd.google-apps.folder'"; //file catched by usiing ! sign
            ChildrenIDsRequest.Fields = "files(id,name)";
            do
            {
                var children = ChildrenIDsRequest.Execute();

                if (children.Items != null && children.Items.Count > 0)
                {
                    foreach (var file in children.Items)
                    {
                        ChildList.Add(file.Id);
                    }
                }
                ChildrenIDsRequest.PageToken = children.NextPageToken;
            } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));

            //Get All File List
            //  List<GoogleDriveFiles> AllFileList = GetDriveFiles();
            List <GoogleDriveFiles> Filter_FileList = new List <GoogleDriveFiles>();


            foreach (string Id in ChildList)
            {
                GoogleDriveFiles File = new GoogleDriveFiles
                {
                    Id          = Id,
                    Name        = "",
                    Size        = 0,
                    Version     = 0,
                    CreatedTime = null
                };
                Filter_FileList.Add(File);
            }
            return(Filter_FileList);
        }
Esempio n. 8
0
        /// <summary>
        /// The entry point of Google Drive Service
        /// </summary>
        public static void initGoogleService()
        {
            DriveCommand.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
            {
                ClientId     = DriveSettings.clientId,
                ClientSecret = DriveSettings.clientSecret,
            },
                new[] { DriveService.Scope.Drive },
                "user",
                CancellationToken.None).Result;

            // Create the service.
            DriveCommand.service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Google Drive Text Pad.",
            });
        }
Esempio n. 9
0
        public async Task <ActionResult> UploadGoogleFileAsync(HttpPostedFileBase file, FileModel document, CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                         AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var service = new GFile.DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = "WorkCard.vn"
                });

                if (file != null)
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = System.IO.Path.GetFileName(file.FileName);
                        var path     = System.IO.Path.Combine(Server.MapPath("~/App_Data/Uploads/GoogleDrives"), fileName);
                        file.SaveAs(path);

                        GDataFile.File _file = new GDataFile.File();
                        _file.Title       = file.FileName;
                        _file.Description = "From WorkCard.vn; ";
                        _file.MimeType    = GetMimeType(file.FileName);
                        _file.CanComment  = true;
                        _file.Shared      = true;
                        _file.Shareable   = true;

                        using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                        {
                            try
                            {
                                GFile.FilesResource.InsertMediaUpload request = service.Files.Insert(_file, stream, _file.MimeType);
                                await request.UploadAsync();

                                if (request.ResponseBody != null)
                                {
                                    Permission permission = new Permission
                                    {
                                        Type     = "anyone",
                                        Role     = "writer",
                                        WithLink = true
                                    };

                                    var a = service.Permissions.Insert(permission, request.ResponseBody.Id);
                                    await a.ExecuteAsync();

                                    using (ApplicationDbContext context = new ApplicationDbContext())
                                    {
                                        document.Id = Guid.NewGuid();
                                        document.Load(request.ResponseBody);
                                        document.CreatedBy   = User.Identity.Name;
                                        document.CreatedDate = DateTime.Now;

                                        context.Files.Add(document);
                                        await context.SaveChangesAsync();
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("An error occurred: " + e.Message);
                            }
                        }
                    }
                    if (Request.IsAjaxRequest())
                    {
                        return(PartialView());
                    }
                }

                return(RedirectToAction("Details", "Articles", new { id = document.ArticleId }));
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }