Пример #1
0
        public static string DeleteFile(string localFilePath, string gFileId)
        {
            IsDeletingFile = true;
            string deleteResult = "";

            if (string.IsNullOrWhiteSpace(gFileId))
            {
                deleteResult = "gFileId is null or empty!";
                return(deleteResult);
            }
            DriveService service = GetGDriveService();

            try
            {
                FilesResource.DeleteRequest deleteRequest = service.Files.Delete(gFileId);
                deleteResult = deleteRequest.Execute();
            }
            catch (Exception e)
            {
                Debug.WriteLine("An error occurred: " + e.Message);
                throw new Exception($"{localFilePath} could not be deleted from GDrive (Id: {gFileId})", e);
            }
            finally { IsDeletingFile = false; }
            service?.Dispose();
            return(deleteResult);
        }
Пример #2
0
 public bool ReleaseSerivce()
 {
     serviceStarted = false;
     driverservice.Dispose();
     driverservice = null;
     return(false);
 }
Пример #3
0
 void IDisposable.Dispose()
 {
     if (_service != null)
     {
         _service.Dispose();
     }
 }
Пример #4
0
 public void Dispose()
 {
     if (_service != null)
     {
         _service.Dispose();
     }
 }
Пример #5
0
        public static FileList GetYesterdaysFiles(string filter)
        {
            IsListingFileWithFilter = true;
            DriveService service = GetGDriveService();
            FileList     files   = null;

            try
            {
                FilesResource.ListRequest listRequest = service.Files.List();
                DateTime ct = DateTime.Now;
                //ct = ct.TimeOfDay.TotalMinutes < 5 ? ct.AddDays(-1).Date : ct;
                listRequest.Q      = filter;
                listRequest.Fields = "files(id, parents, name, createdTime, modifiedTime)";
                files = listRequest.Execute();
            }
            catch (GoogleApiException e)
            {
                Debug.WriteLine("An error occurred: " + e.Message);
                throw;
            }
            catch (Exception e)
            {
                Debug.WriteLine("An error occurred: " + e.Message);
                throw;
            }
            finally { IsListingFileWithFilter = false; }
            service?.Dispose();
            return(files);
        }
Пример #6
0
 /// <summary>
 /// Disposes the Google Drive library.
 /// </summary>
 public void Dispose()
 {
     if (driveService != null)
     {
         driveService.Dispose();
         driveService = null;
     }
 }
Пример #7
0
 public void Logout()
 {
     if (DriveService != null)
     {
         DriveService.Dispose();
     }
     DriveService    = null;
     DriveCredential = null;
 }
Пример #8
0
        public static bool Authorise()
        {
            if (_service != null)
            {
                _service.Dispose();
            }
            _service = null;

            try
            {
                if (_tCancel != null)
                {
                    _tCancel.Cancel(true);
                }

                _tCancel = new CancellationTokenSource();
                var t = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                {
                    ClientId     = "648753488389.apps.googleusercontent.com",
                    ClientSecret = "Guvru7Ug8DrGcOupqEs6fTB1"
                },
                    new[] { DriveService.Scope.Drive },
                    "user", _tCancel.Token);

                t.ContinueWith(p =>
                {
                    if (!p.IsCompleted || p.IsCanceled || p.IsFaulted)
                    {
                        return;
                    }
                    var credential = t.Result;

                    _service = new DriveService(new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = "iSpy",
                    });
                    if (credential != null && credential.Token != null &&
                        credential.Token.RefreshToken != null)
                    {
                        MainForm.Conf.GoogleDriveConfig =
                            _refreshToken = credential.Token.RefreshToken;
                    }
                    _lookups = new List <LookupPair>();
                    _upload  = new List <UploadEntry>();
                });
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
                return(false);
            }

            return(true);
        }
Пример #9
0
        /// <summary>
        /// Dispose method.
        /// </summary>
        /// <param name="disposing">Indicates currently disposing.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // dispose managed resources
                driveService.Dispose();
                driveService = null;
            }

            // free native resources
        }
Пример #10
0
        public override void ClearMountPoint()
        {
            if (!IsMounted)
            {
                return;
            }

            base.ClearMountPoint();

            _driveService.Dispose();
        }
Пример #11
0
        public async Task InitializeSignOut()
        {
            await credential.RevokeTokenAsync(CancellationToken.None);

            service.Dispose();

            service    = null;
            credential = null;

            SignedIn = false;

            this.loginStatusChanged();
        }
Пример #12
0
        public static async Task <IUploadProgress> UploadFile(string uploadFile, Dictionary <string, string> appFileAttributes = null)
        {
            IsUploadingFile = true;
            DriveService    service  = GetGDriveService();
            IUploadProgress progress = null;

            //Task<IUploadProgress> progress = null;
            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File();
                body.Name        = Path.GetFileName(uploadFile);
                _uploadFilename  = body.Name;
                body.Description = FileUploadDescription;
                body.Properties  = appFileAttributes;
                body.MimeType    = GetMimeType(uploadFile);
                //body.Id = DateTime.Now.ToString("dd-HH:mm:ss.fffff");


                try
                {
                    // File's content.
                    byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
                    MemoryStream stream    = new MemoryStream(byteArray);

                    //FilesResource.UpdateMediaUpload uploadRequest = service.Files.Update(f, "", stream, body.MimeType);
                    FilesResource.CreateRequest cr = service.Files.Create(body);
                    File f = cr.Execute();
                    //FilesResource.CreateMediaUpload uploadRequest = service.Files.Create(f, stream, body.MimeType);
                    //uploadRequest.Body.Id = DateTime.Now.ToString("dd-HH:mm:ss.fffff");
                    //body.Id = "WRJskjslkdjslj3q9";
                    FilesResource.CreateMediaUpload uploadRequest = service.Files.Create(body, stream, body.MimeType);
                    //FilesResource.CreateMediaUpload ur = new FilesResource.CreateMediaUpload(service, body, stream, body.MimeType);
                    //uploadRequest.Fields = "Id";
                    //uploadRequest.Body.Properties = new Dictionary<string, string>();
                    //uploadRequest.Body.Properties.Add("sdkjfs", "kdjskjd");
                    uploadRequest.SupportsTeamDrives = true;
                    uploadRequest.ResponseReceived  += UploadRequest_ResponseReceived;
                    uploadRequest.ProgressChanged   += UploadRequest_ProgressChanged;
                    // new Exception("Exception");
                    progress = await uploadRequest.UploadAsync();//.UploadAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("An error occurred: " + e.Message);
                    throw;
                }
                finally { IsUploadingFile = false; }
            }
            service?.Dispose();
            return(progress);// uploadedFile == null ? string.Empty : uploadedFile.Id;
        }
Пример #13
0
        private static async Task AuthorizeAsync()
        {
            Log("Authorizing...");
            //GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_id.json"),
                new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive },
                "user",
                CancellationToken.None);

            Log("Creating service...");
            // Create the service.
            if (_driveService != null)
            {
                _driveService.Dispose();
            }
            _driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName       = "Google Drive APIs",
            });
            Log("Service created!");
        }
Пример #14
0
        public static bool Authorise(string code)
        {
            _service?.Dispose();
            _service = null;

            try
            {
                var request =
                    (HttpWebRequest)
                    WebRequest.Create("https://www.googleapis.com/oauth2/v4/token");

                var postData = "code=" + code + "&client_id=" + MainForm.GoogleClientId +
                               "&client_secret=" + MainForm.GoogleClientSecret +
                               "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code";
                var dp = Encoding.ASCII.GetBytes(postData);

                request.Method        = "POST";
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(dp, 0, postData.Length);
                }

                var    response = (HttpWebResponse)request.GetResponse();
                Stream s        = response.GetResponseStream();
                if (s == null)
                {
                    throw new Exception("null response stream");
                }
                var responseString = new StreamReader(s).ReadToEnd();

                dynamic d = JsonConvert.DeserializeObject(responseString);

                string at = d.access_token.ToString();//test it is authorised

                MainForm.Conf.Cloud.Drive = responseString;
                return(true);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                MainForm.Conf.Cloud.Drive = "";
                return(false);
            }
        }
Пример #15
0
        public static bool Authorise()
        {
            _service?.Dispose();
            _service = null;

            try
            {
                _tCancel?.Cancel(true);

                _tCancel = new CancellationTokenSource();
                var t = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                {
                    ClientId     = "648753488389.apps.googleusercontent.com",
                    ClientSecret = "Guvru7Ug8DrGcOupqEs6fTB1"
                },
                    new[] { DriveService.Scope.Drive },
                    "user", _tCancel.Token, new FileDataStore("Drive")).Result;

                _service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = t,
                    ApplicationName       = "iSpy",
                });
                if (t?.Token?.RefreshToken != null)
                {
                    MainForm.Conf.GoogleDriveConfig =
                        _refreshToken = t.Token.RefreshToken;

                    _service = new DriveService(new BaseClientService.Initializer
                    {
                        HttpClientInitializer = t,
                        ApplicationName       = "iSpy",
                    });
                }
                _lookups = new List <LookupPair>();
                _upload  = new List <UploadEntry>();
            }
            catch (Exception ex)
            {
                Logger.LogExceptionToFile(ex);
                return(false);
            }

            return(true);
        }
Пример #16
0
        public static IUploadProgress UploadFile(string uploadFile, ref File file, Dictionary <string, string> appFileAttributes = null)
        {
            IsUploadingFile = true;
            DriveService    service  = GetGDriveService();
            IUploadProgress progress = null;

            if (System.IO.File.Exists(uploadFile))
            {
                File body = new File();
                body.Name        = Path.GetFileName(uploadFile);
                _uploadFilename  = body.Name;
                body.Description = FileUploadDescription;
                body.Properties  = appFileAttributes;
                body.MimeType    = GetMimeType(uploadFile);
                body.Parents     = new List <string>(new[] { GFolderId });
                //body.Parents.Add(/*"Golden Database Backup(18 - */"wjFxMidgdy9eJbZSY1xCtPIYR8cDgI");
                try
                {
                    // File's content.
                    byte[]       byteArray = System.IO.File.ReadAllBytes(uploadFile);
                    MemoryStream stream    = new MemoryStream(byteArray);
                    FilesResource.CreateMediaUpload uploadRequest = service.Files.Create(body, stream, body.MimeType);
                    uploadRequest.Body.Properties = appFileAttributes;
                    //uploadRequest.Body.Properties.Add("sdkjfs", "kdjskjd");
                    uploadRequest.SupportsTeamDrives = true;
                    uploadRequest.ResponseReceived  += UploadRequest_ResponseReceived;
                    uploadRequest.ProgressChanged   += UploadRequest_ProgressChanged;
                    // new Exception("Exception");
                    progress = uploadRequest.Upload();//.UploadAsync();
                    if (progress.Status == UploadStatus.Completed)
                    {
                        file = uploadRequest.ResponseBody;
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("An error occurred: " + e.Message);
                    throw;
                }
                finally { IsUploadingFile = false; }
            }
            service?.Dispose();
            return(progress);// uploadedFile == null ? string.Empty : uploadedFile.Id;
        }
Пример #17
0
        public static Task <string> DeleteFileAsync(string gFileId)
        {
            IsDeletingFile = true;
            Task <string> deleteTask = null;
            DriveService  service    = GetGDriveService();

            try
            {
                FilesResource.DeleteRequest deleteRequest = service.Files.Delete(gFileId);
                deleteTask = deleteRequest.ExecuteAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine("An error occurred: " + e.Message);
                throw;
            }
            finally { IsDeletingFile = false; }
            service?.Dispose();
            return(deleteTask);
        }
Пример #18
0
        public void TearDown( )
        {
            View.Load -= new EventHandler(View_Load);

            View.SelectedDriveChanged -= new EventHandler(View_SelectedDriveChanged);
            View.SelectedSpeedChanged -= new EventHandler(View_SelectedSpeedChanged);
            View.Eject  -= new EventHandler(View_Eject);
            View.Cancel -= new EventHandler(View_Cancel);
            View.Test   -= new EventHandler(View_Test);
            View.Burn   -= new EventHandler(View_Burn);

            DriveService.SelectedDriveChanged      -= new EventHandler(DriveService_SelectedDriveChanged);
            DriveService.SelectedDriveSpeedChanged -= new EventHandler(DriveService_SelectedDriveSpeedChanged);
            DriveService.SpeedsChanged             -= new EventHandler(DriveService_SpeedsChanged);
            DriveService.SelectedDriveStateChanged -= new EventHandler(DriveService_SelectedDriveStateChanged);

            View.CleanUp( );

            View = null;

            DriveService.Dispose( );
        }
Пример #19
0
        public static string EmptyTrashFolder()
        {
            IsEmptyingTrash = true;
            string       emptyTrashResult = "Error";
            DriveService service          = GetGDriveService();

            try
            {
                FilesResource.EmptyTrashRequest emptyTrashRequest = service.Files.EmptyTrash();
                emptyTrashResult = emptyTrashRequest.Execute();
            }
            catch (GoogleApiException e)
            {
                Debug.WriteLine("An error occurred: " + e.Message);
                throw;
            }
            catch (Exception e) {
                Debug.WriteLine("An error occurred: " + e.Message);
                throw;
            }
            finally { IsEmptyingTrash = false; }
            service?.Dispose();
            return(emptyTrashResult);
        }
Пример #20
0
        public void Close()
        {
            _driveService.Dispose();

            IsOpened = false;
        }
Пример #21
0
 public void Dispose()
 {
     _service?.Dispose();
     _tokenStore?.ClearAsync();
 }
Пример #22
0
 public void Dispose()
 {
     _driveService.Dispose();
 }
Пример #23
0
 public void Dispose()
 {
     _driveService?.Dispose();
     _isAuthorized.Dispose();
 }
Пример #24
0
        public static void UploadFilesToGoogleDriveFolder(int userId, FileInfo[] files)
        {
            DriveService service = RegisterServiceByUserId(userId);

            // Get folder id of evatel sound records
            string folderId = GetGoogleDriveFolderId(Globals.CLOUD_EVATEL_FOLDER, service);

            // Folder has not been existing yet
            if (folderId == null)
            {
                // Create a Evatel folder, and return folder id
                folderId = CreateFolderOnGoogleDriver(Globals.CLOUD_EVATEL_FOLDER, service);
            }

            // Loop files to upload all files
            foreach (FileInfo file in files)
            {
                var FileMetaData = new Google.Apis.Drive.v3.Data.File()
                {
                    Name     = file.Name,
                    MimeType = MimeMapping.GetMimeMapping(file.FullName),
                    Parents  = new List <string>
                    {
                        folderId
                    }
                };


                FilesResource.CreateMediaUpload request;

                using (var stream = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open))
                {
                    request        = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }


                // Clear session
                //System.Web.HttpContext.Current.Session.Remove("uploadedFileName");

                // Check upload result
                var uploadedfile = request.ResponseBody;

                // Set file processing result
                FileProcessingResult result = new FileProcessingResult();
                result.UserId           = userId;
                result.FileName         = file.Name;
                result.CloudStorageType = (byte)User.ServiceType.GoogleDrive;
                result.TimeStamp        = DateTime.Now;

                // Upload successfully
                if (uploadedfile.Id != null)
                {
                    result.IsSuccessful = true;
                }
                // Upload failed
                else
                {
                    result.IsSuccessful = false;
                }

                // Add result to context
                _context.FilesProcessingResults.Add(result);
            }

            // Save to Database;
            _context.SaveChanges();

            service.Dispose();
        }
Пример #25
0
 private void GoogleLoggedOut()
 {
     m_UserData = null;
     m_DriveService.Dispose();
     m_DriveService = null;
 }
Пример #26
0
 public override void Dispose()
 {
     _driveService.Dispose();
 }
Пример #27
0
        static void Main()
        {
            Console.OutputEncoding = Encoding.UTF8;

            // get the first localhost drive
            var settings = Settings.Current.DriveServiceSettings.Where(d => d.BaseUrl.IndexOf("//localhost") > 0).FirstOrDefault();

            if (settings == null)
            {
                Console.WriteLine("Did not found a localhost drive.");
                return;
            }

            Console.WriteLine("Found '" + settings.Name + "' drive.");

            using (var service = new DriveService(settings))
            {
                Console.CancelKeyPress += (s, e) =>
                {
                    Console.ResetColor(); // logger uses colors
                    service.Dispose();
                    Console.WriteLine("Aborted.");
                };

                service.OnDemandSynchronizer.Logger = new Logger();
                Console.WriteLine(" Root Path: " + service.RootPath);
                Console.WriteLine(" Sync Period: " + service.OnDemandSynchronizer.SyncPeriod);

                var rootPath = service.OnDemandSynchronizer.RootPath;
                var waitTime = CommandLine.GetArgument("wait", 500);

                Console.WriteLine();
                Console.WriteLine("Press ESC to quit.");
                Console.WriteLine("Press C to clear.");
                Console.WriteLine("Press N to create files.");
                Console.WriteLine("Press D to delete files.");
                Console.WriteLine("Press R to rename files.");

                do
                {
                    var key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.Escape)
                    {
                        break;
                    }

                    switch (key.Key)
                    {
                    case ConsoleKey.S:
                        service.OnDemandSynchronizer.Synchronize();
                        break;

                    case ConsoleKey.C:
                        Console.Clear();
                        break;

                    case ConsoleKey.N:
                        int max = 10;
                        Console.WriteLine(">>> Creating " + max + " test file(s) under " + rootPath);
                        for (int i = 0; i < max; i++)
                        {
                            var path = Path.Combine(rootPath, "test." + i + ".auto.txt");
                            File.WriteAllText(path, "this is test #" + i + " for path " + path);
                            Thread.Sleep(_rnd.Next(waitTime));
                        }
                        break;

                    case ConsoleKey.D:
                        Console.WriteLine(">>> Deleting all test files under " + rootPath);
                        foreach (var file in Directory.GetFiles(rootPath, "*.auto.txt"))
                        {
                            IOUtilities.FileDelete(file);
                            Thread.Sleep(_rnd.Next(waitTime));
                        }
                        break;

                    case ConsoleKey.R:
                        Console.WriteLine(">>> Renaming all test files under " + rootPath);
                        foreach (var file in Directory.GetFiles(rootPath, "*.auto.txt"))
                        {
                            var newPath = Path.Combine(Path.GetDirectoryName(file), "_" + Path.GetFileName(file));
                            IOUtilities.FileMove(file, newPath);
                            Thread.Sleep(_rnd.Next(waitTime));
                        }
                        break;
                    }
                }while (true);
                Console.ResetColor();
            }
        }