Exemplo n.º 1
0
 /// <summary>
 /// This Method takes in a parent directory as parameter.
 /// Lists all the sub-directories and adds them to the parent directory.
 /// Lists all the files and adds them to the parent directory.
 /// </summary>
 public void GetFiles(DirectoryBlock parentDirectory)
 {
     using (DriveService service = DriveClient.GetInfo())
     {
         try
         {
             FilesResource.ListRequest listRequest = service.Files.List();
             listRequest.Q       = "'" + parentDirectory.id + "' in parents and trashed = false";
             listRequest.OrderBy = "name";
             listRequest.Fields  = "nextPageToken, files" +
                                   "(id, name, mimeType, permissions, webContentLink, description, size, shared, owners, parents)";
             Google.Apis.Drive.v3.Data.FileList ListResponse = listRequest.Execute();
             while (ListResponse.Files != null && ListResponse.Files.Count != 0)
             {
                 List <Task> tasks = new List <Task>();
                 foreach (var item in ListResponse.Files)
                 {
                     tasks.Add(Task.Run(() => AddToParentDirectoryObject(item, parentDirectory)));
                 }
                 Task.WaitAll(tasks.ToArray());
                 if (ListResponse.NextPageToken == null)
                 {
                     break;
                 }
                 listRequest.PageToken = ListResponse.NextPageToken;
                 ListResponse          = listRequest.Execute();
             }
         }
         catch (Exception e)
         {
             throw new Exception(e.StackTrace);
         }
     }
 }
Exemplo n.º 2
0
 public async Task DeleteAllFiles(string fileId)
 {
     using (var client = DriveClient.GetInfo())
     {
         FilesResource.ListRequest listRequest = client.Files.List();
         listRequest.Q       = "'" + fileId + "' in parents and trashed = false";
         listRequest.OrderBy = "name";
         //listRequest.Fields = "nextPageToken, files" +
         //    "(id, name, mimeType, permissions, webContentLink, description, size, shared, owners, parents)";
         Google.Apis.Drive.v3.Data.FileList ListResponse = listRequest.Execute();
         while (ListResponse.Files != null)
         {
             List <Task> tasks = new List <Task>();
             foreach (var item in ListResponse.Files)
             {
                 tasks.Add(Task.Run(() => client.Files.Delete(item.Id).Execute()));
             }
             Task.WaitAll(tasks.ToArray());
             if (ListResponse.NextPageToken == null)
             {
                 break;
             }
             listRequest.PageToken = ListResponse.NextPageToken;
             ListResponse          = listRequest.Execute();
         }
     }
 }
Exemplo n.º 3
0
        public static Google.Apis.Drive.v3.Data.FileList DeleteAfter30(DriveService service, FilesListOptionalParms optional = null)
        {
            DateTime ThirtyDayBeforeToday = DateTime.Now.AddDays(-30);

            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }

                // Building the initial request.
                var request = service.Files.List();

                // Applying optional parameters to the request.
                request.Fields = "nextPageToken, files(createdTime ,id, name, mimeType)";

                var pageStreamer = new Google.Apis.Requests.PageStreamer <Google.Apis.Drive.v3.Data.File, FilesResource.ListRequest, Google.Apis.Drive.v3.Data.FileList, string>(
                    (req, token) => request.PageToken = token,
                    response => response.NextPageToken,
                    response => response.Files);

                var allFiles = new Google.Apis.Drive.v3.Data.FileList();
                allFiles.Files = new List <Google.Apis.Drive.v3.Data.File>();

                foreach (var result in pageStreamer.Fetch(request))
                {
                    if (result.MimeType != "application/vnd.google-apps.folder")
                    {
                        if (result.CreatedTime < ThirtyDayBeforeToday)
                        {
                            service.Files.Delete(result.Id).Execute();
                        }
                        else
                        {
                            Console.WriteLine("Data sie zgdza");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Nie usunięto");
                    }
                }
                return(allFiles);
            }
            catch (Exception Ex)
            {
                throw new Exception("Request Files.List failed.", Ex);
            }
        }
        private async Task <string> FindFile(DriveService service, Func <GoogleData.File, bool> predicate)
        {
            FilesResource.ListRequest listRequest = service.Files.List();
            GoogleData.FileList       fileList    = await listRequest.ExecuteAsync().ConfigureAwait(false);

            foreach (GoogleData.File file in fileList.Files)
            {
                if (predicate(file))
                {
                    return(file.Id);
                }
            }

            return(string.Empty);
        }
Exemplo n.º 5
0
        public void PrettyPrint(DriveService service, Google.Apis.Drive.v3.Data.FileList list, string indent)
        {
            //Array.Clear(nams, 0, 30);
            foreach (var item in list.Files.OrderBy(a => a.Name))
            {
                ids[ty]  = item.Id;
                nams[ty] = (/*string.Format("{0}|-{1}", indent, */ item.Name);
                ty++;

                /*if (item.MimeType == "application/vnd.google-apps.folder")
                 * {
                 *  var ChildrenFiles = ListAll(service, new FilesListOptionalParms { Q = string.Format("('{0}' in parents)", item.Id), PageSize = 1000 });
                 *  PrettyPrint(service, ChildrenFiles, indent + "  ");
                 * }*/
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 取得檔案清單
        /// Documentation List: https://developers.google.com/drive/v2/reference/files/list
        /// Documentation Search: https://developers.google.com/drive/web/search-parameters
        /// </summary>
        /// <param name="searchPattern">搜尋條件</param>
        /// <returns></returns>
        public static List <GData.File> List(DriveService _service, string searchPattern = "*")
        {
            List <GData.File> result = new List <GData.File>();

            try
            {
                FilesResource.ListRequest request = _service.Files.List();
                request.PageSize = 1000;
                request.Fields   = "nextPageToken, files(id, name,parents,mimeType,size,capabilities,modifiedTime,webViewLink,webContentLink)";
                //request.MaxResults = 1000;
                if (searchPattern != "*")
                {
                    request.Q = searchPattern;
                }
                GData.FileList filesFeed = request.Execute();


                // 判斷資料是否回傳結束
                while (filesFeed.Files != null)
                {
                    // add to the list
                    result.AddRange(filesFeed.Files);

                    if (filesFeed.NextPageToken != null)
                    {
                        // 若有下一頁,繼續
                        request.PageToken = filesFeed.NextPageToken;

                        // 執行 NextPage 的 request
                        filesFeed = request.Execute();
                    }
                    else
                    {
                        // 若沒有下一頁,結束
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return(result);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Lists or searches files.
        /// Documentation https://developers.google.com/drive/v3/reference/files/list
        /// Generation Note: This does not always build correctly.  Google needs to standardize things I need to figure out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Drive service. </param>
        /// <param name="optional">The optional parameters. </param>
        /// <returns>FileListResponse</returns>
        ///

        public static Google.Apis.Drive.v3.Data.FileList ListAll(DriveService service, FilesListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }

                // Building the initial request.
                var request = service.Files.List();

                // Applying optional parameters to the request.
                request = (FilesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                var pageStreamer = new Google.Apis.Requests.PageStreamer <Google.Apis.Drive.v3.Data.File, FilesResource.ListRequest, FileList, string>(
                    (req, token) => request.PageToken = token,
                    response => response.NextPageToken,
                    response => response.Files);

                var allFiles = new Google.Apis.Drive.v3.Data.FileList();
                allFiles.Files = new List <Google.Apis.Drive.v3.Data.File>();

                foreach (var result in pageStreamer.Fetch(request))
                {
                    allFiles.Files.Add(result);
                }

                return(allFiles);
            }
            catch (Exception Ex)
            {
                throw new Exception("Request Files.List failed.", Ex);
            }
        }
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                System.Console.WriteLine("Please enter a location to save the files from Google Drive Trash.");
                return(0);
            }

            UserCredential credential;
            string         location = args[0].ToString();

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens
                // It is created automatically when the authorization flow completes for the first time
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });


            List <Google.Apis.Drive.v3.Data.File> files = new List <Google.Apis.Drive.v3.Data.File>();

            Console.WriteLine("Date and Time: " + DateTime.Now);
            Console.WriteLine("Looking for files...");
            int retryNumber     = 0;
            int totalFileNumber = 0;

            Google.Apis.Drive.v3.Data.FileList result = null;

            while (true)
            {
                if (result != null && string.IsNullOrWhiteSpace(result.NextPageToken))
                {
                    break;
                }

                FilesResource.ListRequest listRequest = service.Files.List();
                listRequest.PageSize = 1000;
                listRequest.Fields   = "nextPageToken, files(id, name, trashed, fullFileExtension, size)";
                if (result != null)
                {
                    listRequest.PageToken = result.NextPageToken;
                }

                try
                {
                    result = listRequest.Execute();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error calling Google API. Trying again.");
                    Console.WriteLine(e.Message);
                    Console.WriteLine();
                    retryNumber++;

                    if (retryNumber < 3)
                    {
                        Thread.Sleep(5000); // Pause 10 seconds
                        result = listRequest.Execute();
                    }
                    else
                    {
                        retryNumber = 0;
                        continue;
                    }
                }

                totalFileNumber = totalFileNumber + 1000;
                files.AddRange(result.Files);
                Console.WriteLine("Added 1000 files... Looking for more. Total Files: " + totalFileNumber.ToString());
            }

            //Persist List of Files
            try
            {
                Console.WriteLine(">------------ Begin Saving List to the Hard Disk <------------");
                WriteToJsonFile(string.Format(@location + "{0}", "ListOfFiles"), files, false);
                Console.WriteLine(">------------ End Saving List to the Hard Disk <------------");
            }
            catch { }


            Console.WriteLine(files.Count.ToString() + " Total Files Found in GDrive.");
            Console.WriteLine("Date and Time: " + DateTime.Now);
            Console.WriteLine();

            bool trashflag = false;
            List <Google.Apis.Drive.v3.Data.File> trashfiles = new List <Google.Apis.Drive.v3.Data.File>();

            string[] lines      = { };
            int      filesizeMB = 0;

            List <String> filenameslist = new List <String>();

            try
            {
                if (files != null && files.Count > 0)
                {
                    foreach (var file in files)
                    {
                        try
                        {
                            trashflag = (bool)file.Trashed;
                        }
                        catch
                        {
                            trashflag = false;
                        }

                        if (trashflag)
                        {
                            trashfiles.Add(file);
                            filesizeMB = 0; // int.Parse(file.Size.ToString()) / 1000;

                            Console.WriteLine("[TRASH - ] {0} ({1}), {2}, {3} Kb ({4} MB)", file.Name, file.Id, file.FileExtension, file.Size, filesizeMB);
                            filenameslist.Add(file.Name + "," + file.Id);

                            try
                            {
                                if (System.IO.File.Exists(string.Format(@location + "{0}", file.Name)))
                                {
                                    //Console.WriteLine("File exists locally...Skipped.");
                                }
                                else
                                {
                                    Console.WriteLine("File does not exist locally. Downloading.");
                                    //If it fails , try again once

                                    try
                                    {
                                        DownloadFile(service, file, string.Format(@location + "{0}", file.Name));
                                    }
                                    catch (Exception e)
                                    {
                                        if (e.Message.Contains("Download failed."))
                                        {
                                            DownloadFile(service, file, string.Format(@location + "{0}", file.Name));
                                        }
                                        if (e.Message.Contains("binary"))
                                        {
                                            Console.WriteLine("Skipping Non-Binary File.");
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                Console.WriteLine("Could not download {0}", file.Name);
                            }
                        }
                        else
                        {
                            //Console.WriteLine("{0} ({1}), {2}, {3}Kb", file.Name, file.Id, file.FileExtension, file.Size);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No files found.");
                }
            }
            catch { }

            Console.WriteLine();
            Console.WriteLine("Writing list of files in the trash to a text file.");
            System.IO.File.WriteAllLines(@location + "WriteLinesFinal.txt", filenameslist);

            Console.WriteLine();
            Console.WriteLine("Done. Press Any Key.");

            Console.Read();
            return(0);
        }