public static string compressFile(string path)
        {
            string zipPath = path.Split('.').First() + ".zip";

            try
            {
                using (ZipFile zip = new ZipFile(Encoding.UTF8))
                {
                    if (Path.HasExtension(path))
                    {
                        zip.AddFile(@path);
                    }
                    else
                    {
                        zip.AddDirectory(@path);
                    }
                    zip.Save(@zipPath);
                }
                return(@zipPath);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Compress IO.File Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Compress IO.File Error.\n");
                return(null);
            }
        }
        public static string createFolderToDrive(string folderName, string parentId)
        {
            try
            {
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name     = folderName,
                    MimeType = "application/vnd.google-apps.folder",
                };
                if (parentId != null)
                {
                    fileMetadata.Parents = new List <string>
                    {
                        parentId
                    };
                }

                var request = driveService.Files.Create(fileMetadata);
                request.Fields = "id";
                var file = request.Execute();
                System.Diagnostics.Debug.WriteLine("{0} {1}", file.Name, file.Id);
                return(file.Id);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Create Folder to Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Create Folder to Drive Error.\n");
                return(null);
            }
        }
        private static bool getCredential(string clientSecretPath, string userName)
        {
            string savePath = Path.Combine(appDataSavePath, Path.GetFileName(clientSecretPath));

            if (System.IO.File.Exists(savePath))
            {
                try
                {
                    using (var stream = new FileStream(savePath, FileMode.Open, FileAccess.Read))
                    {
                        string credPath = Path.Combine(appDataSavePath, ".credentials");

                        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                            GoogleClientSecrets.Load(stream).Secrets,
                            Scopes,
                            "Drive-" + userName,
                            CancellationToken.None,
                            new FileDataStore(credPath, true)).Result;
                    }
                    return(true);
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.Message + " Get Credential Error");
                    Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                       Environment.NewLine + exc.Message + " Get Credential Error.\n");
                    return(false);
                }
            }
            else
            {
                System.IO.File.Copy(clientSecretPath, Path.Combine(appDataSavePath, Path.GetFileName(clientSecretPath)));
                return(getCredential(clientSecretPath, userName));
            }
        }
 public static void removeFile(string fileID)
 {
     try
     {
         var request = driveService.Files.Delete(fileID);
         request.Execute();
     }
     catch (Exception exc)
     {
         System.Diagnostics.Debug.WriteLine(exc.Message + " Remove Drive File error");
         Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                            Environment.NewLine + exc.Message + " Remove Drive File Error.\n");
     }
 }
Esempio n. 5
0
        private void saveFileLIst(string saveFile)
        {
            try
            {
                string contentsToWriteToFile = JsonConvert.SerializeObject(IOFileList.ToArray(), Newtonsoft.Json.Formatting.Indented);

                System.IO.File.WriteAllText(saveFile, contentsToWriteToFile);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Save User Error.\n");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Save User Error.\n");
            }
        }
Esempio n. 6
0
        private static void startWithArgs(string[] args)
        {
            string uploadFilePath, filename, backupName, parentID;
            int    user, compressing = 0, onlyNew = 0;

            try
            {
                if (loadUsers() && args.Length > 5)
                {
                    loadFileList(args[0]);
                    backupName = args[1];
                    parentID   = (args[2] != "0") ? args[2] : null;
                    int.TryParse(args[3], out user);
                    int.TryParse(args[4], out onlyNew);
                    int.TryParse(args[5], out compressing);


                    if (GoogleDriveAPIV3.GoogleDriveConnection(
                            UserList[user].clientSecretPath,
                            UserList[user].userName))
                    {
                        parentID = GoogleDriveAPIV3.createFolderToDrive(
                            Gtools.getTimeStamp() + "_" + backupName,
                            parentID);
                        foreach (IOFile file in IOFileList)
                        {
                            uploadFilePath = (compressing == 0) ? file.path : Gtools.compressFile(file.path);
                            filename       = (compressing == 0) ? file.name : file.name.Split('.').First() + ".zip";
                            GoogleDriveAPIV3.uploadToDrive(uploadFilePath, filename, parentID, (onlyNew != 0), new frmMain());
                        }
                    }
                    else
                    {
                        throw new Exception("Connection Error");
                    }
                }
                else
                {
                    throw new Exception("Arguments Error");
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Start with Args Error.\n");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Start with Args Error.\n");
            }
        }
        public static List <GoogleCaledar> listCalendar()
        {
            List <GoogleCaledar> calList = new List <GoogleCaledar>();

            try
            {
                EventsResource.ListRequest request = calendarService.Events.List("primary");
                request.TimeMin      = DateTime.Now;
                request.ShowDeleted  = false;
                request.SingleEvents = true;
                request.MaxResults   = 10;
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

                // List events.
                Events events = request.Execute();
                System.Diagnostics.Debug.WriteLine("Upcoming events:");
                if (events.Items != null && events.Items.Count > 0)
                {
                    foreach (var eventItem in events.Items)
                    {
                        string when = eventItem.Start.DateTime.ToString();
                        if (String.IsNullOrEmpty(when))
                        {
                            when = eventItem.Start.Date;
                        }
                        System.Diagnostics.Debug.WriteLine("{0} ({1})", eventItem.Summary, when);
                        calList.Add(new GoogleCaledar(eventItem.Summary, when, eventItem.UpdatedRaw.ToString(), eventItem.Status, eventItem.Id));
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("No upcoming events found.");
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Create Drive Service Error.\n");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Create Drive Service Error.\n");
            }

            return(calList);
        }
        private static void convertMemoryStreamToFileStream(MemoryStream stream, string savePath)
        {
            FileStream fileStream;

            using (fileStream = new System.IO.FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                try
                {
                    // System.IO.File.Create(saveFile)
                    stream.WriteTo(fileStream);
                    fileStream.Close();
                }
                catch (Exception exc)
                {
                    System.Diagnostics.Debug.WriteLine(exc.Message + " Convert Memory stream Error");
                    Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                       Environment.NewLine + exc.Message + " Convert Memory stream Error.\n");
                }
            }
        }
 private static bool createDriveService()
 {
     try
     {
         // Create Drive API service.
         driveService = new DriveService(new BaseClientService.Initializer()
         {
             HttpClientInitializer = credential,
             ApplicationName       = applicationName,
         });
         return(true);
     }
     catch (Exception exc)
     {
         System.Diagnostics.Debug.WriteLine(exc.Message + " Create Drive Service Error.\n");
         Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                            Environment.NewLine + exc.Message + " Create Drive Service Error.\n");
         return(false);
     }
 }
        public static void directoryUpload(string path, string parentId, bool onlyNew, frmMain parentForm)
        {
            try
            {
                // Get the subdirectories for the specified directory.
                string folderId = createFolderToDrive(
                    Path.GetFileName(path),
                    parentId);

                System.Diagnostics.Debug.WriteLine(folderId);

                DirectoryInfo dir = new DirectoryInfo(path);
                if (!dir.Exists)
                {
                    throw new DirectoryNotFoundException(
                              "Source directory does not exist or could not be found: "
                              + path);
                }

                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    uploadFileToDrive(
                        folderId, file.Name,
                        Path.Combine(path, file.Name),
                        getMimeType(file.Name), onlyNew, parentForm);
                }

                DirectoryInfo[] dirs = dir.GetDirectories();
                foreach (DirectoryInfo subdir in dirs)
                {
                    directoryUpload(subdir.FullName, folderId, onlyNew, parentForm);
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Directory upload Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Directory upload Error.\n");
            }
        }
Esempio n. 11
0
        private static bool loadFileList(string saveFile)
        {
            try
            {
                if (!System.IO.File.Exists(saveFile))
                {
                    throw new Exception("File not found!");
                }

                IOFileList.Clear();
                IOFileList = Newtonsoft.Json.JsonConvert.DeserializeObject <List <IOFile> >(System.IO.File.ReadAllText(saveFile));
                return(true);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Load User Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Load User Error.\n");
                return(false);
            }
        }
Esempio n. 12
0
 private void loadUsers(string savePath, string saveFile)
 {
     Directory.CreateDirectory(savePath);
     try
     {
         if (System.IO.File.Exists(saveFile))
         {
             UserList.Clear();
             UserList = JsonConvert.DeserializeObject <List <User> >(System.IO.File.ReadAllText(saveFile));
         }
         else
         {
             Gtools.createFile(saveFile, "[ ]");
             loadUsers(savePath, saveFile);
         }
     }
     catch (Exception exc)
     {
         System.Diagnostics.Debug.WriteLine(exc.Message + " Load User Error.\n");
         Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                            Environment.NewLine + exc.Message + " Load User Error.\n");
     }
 }
        public static List <GoogleDriveFile> listDriveFiles(string fileName = null, string fileType = null)
        {
            List <GoogleDriveFile> filesList = new List <GoogleDriveFile>();

            try
            {
                if (fileName == null && fileType == null)
                {
                    FilesResource.ListRequest listRequest = driveService.Files.List();
                    listRequest.PageSize = 1000;
                    listRequest.Fields   = "nextPageToken, files(mimeType, id, name, parents, size, modifiedTime, md5Checksum, webViewLink)";
                    //listRequest.OrderBy = "mimeType";
                    // List files.
                    IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
                    filesList.Clear();
                    if (files != null && files.Count > 0)
                    {
                        foreach (var file in files)
                        {
                            filesList.Add(new GoogleDriveFile(
                                              file.Name,
                                              sizeFix(file.Size.ToString(), file.MimeType),
                                              file.ModifiedTime.ToString(),
                                              file.MimeType,
                                              file.Id, file.Md5Checksum,
                                              file.WebViewLink));
                            System.Diagnostics.Debug.WriteLine("{0} {1} {2} {3}",
                                                               file.Name, file.Id, file.MimeType, file.Size.ToString());
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("No files found.");
                    }
                }
                else
                {
                    string pageToken = null;
                    do
                    {
                        FilesResource.ListRequest request = driveService.Files.List();
                        request.PageSize = 1000;
                        //request.Q = "mimeType='image/jpeg'";
                        request.Q = "name contains '" + fileName + "'";
                        if (fileType != null)
                        {
                            request.Q += "and (mimeType contains '" + fileType + "')";
                        }
                        request.Spaces    = "drive";
                        request.Fields    = "nextPageToken, files(mimeType, id, name, parents, size, modifiedTime, md5Checksum, webViewLink)";
                        request.PageToken = pageToken;
                        var result = request.Execute();
                        foreach (var file in result.Files)
                        {
                            filesList.Add(new GoogleDriveFile(
                                              file.Name,
                                              sizeFix(file.Size.ToString(), file.MimeType),
                                              file.ModifiedTime.ToString(),
                                              file.MimeType,
                                              file.Id, file.Md5Checksum,
                                              file.WebViewLink));
                        }
                        pageToken = result.NextPageToken;
                    } while (pageToken != null);
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Drivefile list Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Drivefile list Error.\n");
            }
            return(filesList);
        }
        public static void downloadFromDrive(string filename, string fileId, string savePath, string mimeType, frmMain parentForm)
        {
            frmMain parent    = parentForm;
            long    totalSize = 100000;

            parent.updateStatusBar(0, "Downloading...");
            try
            {
                if (Path.HasExtension(filename))
                {
                    var request = driveService.Files.Get(fileId);

                    var stream = new System.IO.MemoryStream();
                    System.Diagnostics.Debug.WriteLine(fileId);
                    // Add a handler which will be notified on progress changes.
                    // It will notify on each chunk download and when the
                    // download is completed or failed.
                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            System.Diagnostics.Debug.WriteLine(progress.BytesDownloaded);

                            parent.updateStatusBar((progress.BytesDownloaded * 100) / totalSize, "Downloading...");
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Download complete.");
                            System.Diagnostics.Debug.WriteLine("Download complete.");
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Download failed.");
                            System.Diagnostics.Debug.WriteLine("Download failed.");
                            MessageBox.Show("File failed to download!!!", "Download Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                    convertMemoryStreamToFileStream(stream, savePath + @"\" + @filename);
                    stream.Dispose();
                }
                else
                {
                    string extension = "", converter = "";
                    foreach (MimeTypeConvert obj in MimeConverter.mimeList())
                    {
                        if (mimeType == obj.mimeType)
                        {
                            extension = obj.extension;
                            converter = obj.converterType;
                        }
                    }
                    System.Diagnostics.Debug.WriteLine("{0} {1} {2}", fileId, extension, mimeType);
                    var request = driveService.Files.Export(fileId, converter);
                    var stream  = new System.IO.MemoryStream();
                    // Add a handler which will be notified on progress changes.
                    // It will notify on each chunk download and when the
                    // download is completed or failed.
                    request.MediaDownloader.ProgressChanged +=
                        (IDownloadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case DownloadStatus.Downloading:
                        {
                            Console.WriteLine(progress.BytesDownloaded);
                            break;
                        }

                        case DownloadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Download Complete!");
                            Console.WriteLine("Download complete.");
                            break;
                        }

                        case DownloadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Download failed.");
                            Console.WriteLine("Download failed.");
                            MessageBox.Show("File failed to download!!!", "Download Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        }
                    };
                    request.Download(stream);
                    convertMemoryStreamToFileStream(stream, savePath + @"\" + @filename + extension);
                    stream.Dispose();
                }
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Download From Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Download From Drive.\n");
            }
        }
        private static bool uploadFileToDrive(string folderId, string fileName, string filePath, string fileType, frmMain parentForm)
        {
            frmMain parent = parentForm;

            parent.updateStatusBar(0, "Uploading...");
            long totalSize = 100000;

            try
            {
                FileInfo fi = new FileInfo(filePath);
                totalSize = fi.Length;

                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = fileName
                };
                if (folderId != null)
                {
                    fileMetadata.Parents = new List <string>
                    {
                        folderId
                    };
                }
                FilesResource.CreateMediaUpload request;
                using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
                {
                    request = driveService.Files.Create(
                        fileMetadata, stream, fileType);
                    request.ChunkSize        = FilesResource.CreateMediaUpload.MinimumChunkSize;
                    request.ProgressChanged += (IUploadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case UploadStatus.Uploading:
                        {
                            parent.updateStatusBar((progress.BytesSent * 100) / totalSize, "Uploading...");
                            System.Diagnostics.Debug.WriteLine(progress.BytesSent);
                            break;
                        }

                        case UploadStatus.Completed:
                        {
                            parent.updateStatusBar(100, "Upload complete.");
                            System.Diagnostics.Debug.WriteLine("Upload complete.");
                            break;
                        }

                        case UploadStatus.Failed:
                        {
                            parent.updateStatusBar(0, "Upload failed.");
                            System.Diagnostics.Debug.WriteLine("Upload failed.");
                            //MessageBox.Show("File failed to upload!!!", "Upload Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                               Environment.NewLine + "Upload failed.\n");
                            break;
                        }
                        }
                    };
                    request.Fields = "id";
                    request.Upload();
                }
                var file = request.ResponseBody;
                System.Diagnostics.Debug.WriteLine("File ID:{0} \n FileName {1} ", file.Id, file.Name);
                return(true);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.Message + " Upload file to Drive Error");
                Gtools.writeToFile(frmMain.errorLog, Environment.NewLine + DateTime.Now.ToString() +
                                   Environment.NewLine + exc.Message + " Upload file to Drive Error.\n");
                return(false);
            }
        }