Google云端硬盘 - 在一台计算机上授权一次

时间:2014-07-02 08:19:07

标签: google-app-engine google-drive-api google-docs-api

我是Google云端硬盘的新用户,并且有以下几种我无法找到的方案(不确定是否存在) - >我正在创建一个基于SAAS的Windows应用程序。不同的用户将在其下注册并创建他们的公司登录和子用户。现在我希望他们将google驱动器凭据放在其中一个表单中,这应该适用于其他用户。目前的问题是,虽然开发我完成了谷歌登录,但它从未要求再次登录,但在使用不同登录的其他系统上进行测试时,它一直要求谷歌登录。我只是希望管理员用户放置他们的谷歌驱动器凭据,它应该适用于上传和下载该公司的所有用户的文件。

- >我想在谷歌驱动器上保留相同文件的版本(就像默认情况下谷歌驱动器一样)。让我们说用户A上传了文件xyz然后用户B下载并更改了文件xyz并再次将其上传到驱动器上。 我想在这里做两件事 - 只有上传的内容才会上传而不是整个文件(这样可以节省用户的时间) 我想拥有相同文件的历史记录,以便在Windows应用程序中显示

    #region Get Service Object
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                    {
                        ClientId = "GoogleDriveClientID",
                        ClientSecret = "GoogleDriveClientSecret"
                    },
                    new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;


            // Create the service.
            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "AppName",
            });
#endregion


#region Uploading
public void uploadOnGoogleDrive(ObservableCollection<JobAttachments> AttachmentsColl, bool IsDocSaved)
        {
            try
            {
                service = getServiceObject();

                List<Google.Apis.Drive.v2.Data.File> fileList = retrieveAllFiles(service);
                List<Google.Apis.Drive.v2.Data.File> directoryList = GetDirectoryList(service);

                if (IsDocSaved)
                {
                    #region for checking if the file already exists
                    foreach (Google.Apis.Drive.v2.Data.File item in fileList)
                    {
                        foreach (JobAttachments attach in AttachmentsColl)
                        {
                            if (item.Title == attach.AttachmtGUID)
                            {                               
                                MessageBoxResult result = System.Windows.MessageBox.Show(LogMessages.GetResourceMessage(LogMessages.MessageEnumeration.GD_AlreadyExistsMsg), "Confirmation", MessageBoxButton.YesNoCancel);

                                if (result == MessageBoxResult.Yes)
                                {
                                    //DeleteFile(service, item);
                                    Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
                                    body.Title = attach.AttachmtGUID;
                                    body.MimeType = item.MimeType;
                                    fileSize = body.FileSize;
                                    byte[] byteArray = System.IO.File.ReadAllBytes(attach.AttachmentName);
                                    System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                                    FilesResource.UpdateMediaUpload request = service.Files.Update(body, item.Id, stream, item.MimeType);

                                    request.Upload();
                                }
                                else
                                {
                                    return;
                                }
                                break;
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    #region for direct uploading on google drive
                    if (AttachmentsCollection != null && AttachmentsCollection.Count > 0)
                    {
                        string folderID = string.Empty;
                        if (_IsProject)
                        {
                            if (directoryList != null && directoryList.Count > 0)
                            {
                                foreach (var dir in directoryList)
                                {
                                    if (dir.Title.Equals(_ProjectName))
                                    {
                                        folderID = dir.Id;
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(folderID))
                            {
                                Google.Apis.Drive.v2.Data.File foldbody = new Google.Apis.Drive.v2.Data.File();
                                foldbody.Title = _ProjectName;
                                foldbody.MimeType = "application/vnd.google-apps.folder";
                                foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
                                Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
                                folderID = file.Id;
                            }
                        }
                        else
                        {
                            //project folder
                            string prjFolder = string.Empty;
                            string tskFolder = string.Empty;
                            Google.Apis.Drive.v2.Data.File foldbody;
                            if (directoryList != null && directoryList.Count > 0)
                            {
                                foreach (var dir in directoryList)
                                {
                                    if (dir.Title.Equals(_ProjectName))
                                    {
                                        prjFolder = dir.Id;
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(prjFolder))
                            {
                                foldbody = new Google.Apis.Drive.v2.Data.File();
                                foldbody.Title = _ProjectName;
                                foldbody.MimeType = "application/vnd.google-apps.folder";
                                foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
                                Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
                                prjFolder = file.Id;
                            }

                            //task folder
                            if (directoryList != null && directoryList.Count > 0)
                            {
                                foreach (var dir in directoryList)
                                {
                                    if (dir.Title.Equals(_TaskName) && dir.Parents[0].Id.Equals(prjFolder))
                                    {
                                        folderID = dir.Id;
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrWhiteSpace(folderID))
                            {
                                foldbody = new Google.Apis.Drive.v2.Data.File();
                                foldbody.Title = _TaskName;
                                foldbody.MimeType = "application/vnd.google-apps.folder";
                                foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = prjFolder } };
                                Google.Apis.Drive.v2.Data.File file1 = service.Files.Insert(foldbody).Execute();
                                folderID = file1.Id;
                            }
                        }

                        foreach (JobAttachments item in AttachmentsColl)
                        {
                            if (!string.IsNullOrEmpty(item.AttachmentName))
                            {
                                Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
                                body.Title = item.AttachmtGUID;
                                body.MimeType = item.MimeType;
                                body.Parents = new List<ParentReference>() { new ParentReference() { Id = folderID } };
                                //fileSize = body.FileSize;
                                byte[] byteArray = System.IO.File.ReadAllBytes(item.AttachmentName);
                                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

                                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, item.MimeType);

                                request.Upload();
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    throw ex.InnerException;
            }
        }
#endregion

#region Download File
  private async Task DownloadFile(DriveService service, string url, string title, long? fSize)
        {
 service = getServiceObject();

 var downloader = new MediaDownloader(service);
                //downloader.ChunkSize = 256 * 1024;
                downloader.ProgressChanged += Download_ProgressChanged;
                var fileName = string.Empty;

//for downloading on system
                    var SaveFileDialog = new SaveFileDialog();
                    SaveFileDialog.Title = "Save As";
                    SaveFileDialog.FileName = title;
                    Nullable<bool> result = SaveFileDialog.ShowDialog();

                    if (result == true)
                        fileName = SaveFileDialog.FileName;
                    else if (result == false)
                    {
                        prgrsBar.StyleSettings = new ProgressBarStyleSettings();
                        prgrsBar.Value = 0;
                        return;
                    }
                    else
                    {
                        if (Directory.Exists(@"\Downloads"))
                            fileName = @"\Downloads\" + title;
                    }

 if (!string.IsNullOrWhiteSpace(fileName))
                    using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        fileSize = fSize;
                        var progress = await downloader.DownloadAsync(url, fileStream); 

                        if (progress.Status.ToString() == DownloadStatus.Completed.ToString())
                        {
                            fName = fileStream.Name;
                            prgrsBar.StyleSettings = new ProgressBarStyleSettings();
                            prgrsBar.Value = 0;
                            fileStream.Flush();
                        }
                        if (progress.Status.ToString() == DownloadStatus.Failed.ToString())
                        {
                            HandleDocuments.IsEditButtonClicked = false;
                            MessageBox.Show("Failed......." + progress.Exception.Message);
                        }
                    }
}

#endregion


#region Delete File
 private Task DeleteFile(DriveService service, Google.Apis.Drive.v2.Data.File file)
        {
        service = getServiceObject(); //comment this if calling from another function; create the service object in that function and pass it as parameter to this function.
            service.Files.Delete(file.Id).ExecuteAsync();
            service.Files.EmptyTrash();
            return null;
        }
#endregion


#region Get all Directories and Files from Google Drive
        public List<Google.Apis.Drive.v2.Data.File> GetDirectoryList(DriveService service)
        {
            //Creating the global list
           List<Google.Apis.Drive.v2.Data.File> AllDirectories = new List<Google.Apis.Drive.v2.Data.File>();

            //setting up the Request.
            FilesResource.ListRequest request = service.Files.List();
            //MaxResults: How many we want back at a time max is 1000
            request.MaxResults = 1000;
            //Q: Search results. all i want are folders that havent been trashed (deleted)
            request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";

            do
            {
                try
                {
                    // getting the results
                    FileList files = request.Execute();
                    // adding the results to the list.
                    AllDirectories.AddRange(files.Items);
                    // If there are more results then your MaxResults you will have a nextPageToken to get the rest of the results.
                    request.PageToken = files.NextPageToken;
                }
                catch (Exception ex)
                {
                    request.PageToken = null;
                    if (ex.InnerException != null)
                        throw ex.InnerException;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            List<Google.Apis.Drive.v2.Data.File> DirsInRoot = AllDirectories.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().IsRoot.Value : false).ToList<Google.Apis.Drive.v2.Data.File>();

            List<string> HirearcyList = new List<string>();
            // The first Dir is Root it doesnt get returned. But we need it if we 
            //   Want to be able to list the files that are in the root dir.
            HirearcyList.Add("Root");

            // recersive magic here.
            foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInRoot)
            {
                HirearcyList.Add("     " + myDir.Title);
                HirearcyList.AddRange(RecsiveDir(AllDirectories, myDir.Id, "     "));
            }
            return AllDirectories;
        }

        public List<String> RecsiveDir(List<Google.Apis.Drive.v2.Data.File> allDirs, string ParentId, string Prefix)
        {
            List<string> result = new List<string>();
            List<Google.Apis.Drive.v2.Data.File> DirsInParentId = allDirs.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().Id == ParentId : false).ToList<Google.Apis.Drive.v2.Data.File>();

            foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInParentId)
            {
                result.Add(Prefix + myDir.Title);
                result.AddRange(RecsiveDir(allDirs, myDir.Id, Prefix + "     "));
            }
            return result;
        }

        public static List<Google.Apis.Drive.v2.Data.File> retrieveAllFiles(DriveService service)
        {
            List<Google.Apis.Drive.v2.Data.File> result = new List<Google.Apis.Drive.v2.Data.File>();
            FilesResource.ListRequest request = service.Files.List();
            request.MaxResults = 1000;
            do
            {
                try
                {
                    FileList files = request.Execute();
                    result.AddRange(files.Items);
                    request.PageToken = files.NextPageToken;
                    //service.Revisions.List(files.Items[0].Id) // for getting the file Revision history
                }
                catch (Exception ex)
                {
                    request.PageToken = null;
                    if (ex.InnerException != null)
                        throw ex.InnerException;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));
            return result;
        }
#endregion

由于 Jatinder

0 个答案:

没有答案