public static void Update(Google.Apis.Drive.v2.Data.File file) { try { Load(); if (file == null) { return; } _Mutex.Wait(); try { int index = -1; Update(file, ref index); } finally { _Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); } }
protected static int IndexOf(Google.Apis.Drive.v2.Data.File file) { try { int index = -1; for (int i = 0; i < _Items.Count; i++) { Item item = _Items[i]; if (file.Id == item.Id) { index = i; break; } } return(index); } catch (Exception exception) { Log.Error(exception); return(-1); } }
public static string uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Automatski generirani fajl.") { Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = _descrp; body.MimeType = GetMimeType(_uploadFile); var stream = new System.IO.FileStream(_uploadFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); TotalSize = stream.Length; FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.ProgressChanged += UploadProgessEvent; request.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize; // Minimum ChunkSize allowed by Google is 256*1024 bytes. ie 256KB. var test = request.Upload(); if (test.Exception == null) { return(null); } else { return(test.Exception.Message); } }
private static void DownloadFile(DriveService service, Google.Apis.Drive.v2.Data.File file, string saveTo) { var request = service.Files.Get(file.Id); 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 += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case Google.Apis.Download.DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case Google.Apis.Download.DownloadStatus.Completed: { Console.WriteLine("Download complete."); SaveStream(stream, saveTo); break; } case Google.Apis.Download.DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); }
/** * This class is the one in charge of uploading the file to Drve * @service: DriveService to make the request * return: The webContentLink from the uploaded file that will be neccesary for the dowload of the file later on, * this link will be stored into the database to retrived to the view later. * **/ public static string UploadFileToDrive(DriveService service, string fileName, string filePath, string contentType) { var fileMetadata = new File(); fileMetadata.LastModifyingUserName = fileName; fileMetadata.Title = fileName; FilesResource.InsertMediaUpload request; //----------Esto se cambia por el archivo recibido por el WebService using (var stream = new FileStream(_filePath, FileMode.Open)) { request = service.Files.Insert(fileMetadata, stream, ""); request.Upload(); } //----------------------------------- var file = request.ResponseBody; return(file.WebContentLink); }
public File ToFile(DriveFile driveFile) { if (driveFile == null) { return(null); } if (driveFile is ErrorDriveEntry) { //Return error entry return(ToErrorFile(driveFile as ErrorDriveEntry)); } return(new File { ID = MakeId(driveFile.Id), Access = FileShare.None, ContentLength = driveFile.FileSize.HasValue ? (long)driveFile.FileSize : 0, CreateBy = GoogleDriveProviderInfo.Owner, CreateOn = driveFile.CreatedDate.HasValue ? TenantUtil.DateTimeFromUtc(driveFile.CreatedDate.Value) : default(DateTime), FileStatus = FileStatus.None, FolderID = MakeId(GetParentDriveId(driveFile)), ModifiedBy = GoogleDriveProviderInfo.Owner, ModifiedOn = driveFile.ModifiedDate.HasValue ? TenantUtil.DateTimeFromUtc(driveFile.ModifiedDate.Value) : default(DateTime), NativeAccessor = driveFile, ProviderId = GoogleDriveProviderInfo.ID, ProviderKey = GoogleDriveProviderInfo.ProviderKey, Title = MakeFileTitle(driveFile), RootFolderId = MakeId(), RootFolderType = GoogleDriveProviderInfo.RootFolderType, RootFolderCreator = GoogleDriveProviderInfo.Owner, SharedByMe = false, Version = 1 }); }
protected DriveFile GetDriveEntry(object entryId) { DriveFile entry = null; Exception e = null; var driveId = MakeDriveId(entryId); try { if (!CacheEntry.TryGetValue(GoogleDriveProviderInfo.ID + driveId, out entry)) { entry = GoogleDriveProviderInfo.Storage.GetEntry(driveId); CacheEntry.TryAdd(GoogleDriveProviderInfo.ID + driveId, entry); } } catch (Exception ex) { e = ex; } if (entry == null) { //Create error entry entry = new ErrorDriveEntry(e, driveId); } return(entry); }
public override Directory CreateDirectory(string name) { if (!Storage.IsNameValid(name)) { throw new ArgumentException("The specified name contains invalid characters"); } Google.Apis.Drive.v2.Data.File folder = new Google.Apis.Drive.v2.Data.File(); folder.Title = name; folder.Parents = new List <Google.Apis.Drive.v2.Data.ParentReference>() { new Google.Apis.Drive.v2.Data.ParentReference() { Id = this.folder.Id } }; folder.MimeType = MimeType; var request = storage.Service.Files.Insert(folder); request.Execute(); return(new GoogleDriveDirectory(storage, this, folder)); }
public static void Remove(Google.Apis.Drive.v2.Data.File file) { try { Load(); if (file == null) { return; } _Mutex.Wait(); try { int index = IndexOf(file); if (index > -1) { _Items.RemoveAt(index); } } finally { _Mutex.Release(); } } catch (Exception exception) { Log.Error(exception); } }
public YAGMRC.GoogleStorage.GoogleDrive.GoogleStorageResult Execute(string user, Game game, FileInfo dbFile, FileInfo savedGame) { try { Trace.TraceInformation("Uploading to google"); GoogleDrive storage = new GoogleDrive(user); var rootFolder = storage.GetRootFolder(); Google.Apis.Drive.v2.Data.File gameFolder = storage.AddFolder(game.ID.ToString(), rootFolder.Id); Google.Apis.Drive.v2.Data.File dbFileAtGoogle = storage.InsertFile(dbFile, gameFolder); string dbFileAtGoogleID = storage.ShareFileOrFolder(dbFileAtGoogle); Google.Apis.Drive.v2.Data.File savedGameFileAtGoogle = storage.InsertFile(savedGame, gameFolder); string savedGameFileAtGoogleID = storage.ShareFileOrFolder(savedGameFileAtGoogle); return(new YAGMRC.GoogleStorage.GoogleDrive.GoogleStorageResult() { DatabaseFileID = dbFileAtGoogleID, GameFileID = savedGameFileAtGoogleID }); } catch (Exception e) { throw new GoogleDriveException("An error occurred: " + Environment.NewLine + e.Message); } }
/// <summary> /// Upload file with conversion. /// </summary> /// <param name="filePath"></param> /// <returns>Inserted file id if successful, null otherwise.</returns> public static string DriveUploadWithConversion(string filePath) { try { /* Load pre-authorized user credentials from the environment. * TODO(developer) - See https://developers.google.com/identity for * guides on implementing OAuth2 for your application. */ GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(DriveService.Scope.Drive); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Drive API Snippets" }); // Upload file My Report on drive var fileMetadata = new Google.Apis.Drive.v2.Data.File() { Title = "My Report", MimeType = "application/vnd.google-apps.spreadsheet" }; FilesResource.InsertMediaUpload request; using (var stream = new FileStream(filePath, FileMode.Open)) { // Create a new file, with metadata and stream. request = service.Files.Insert( fileMetadata, stream, "text/csv"); request.Fields = "id"; request.Upload(); } var file = request.ResponseBody; // Prints the uploaded file id. Console.WriteLine("File ID: " + file.Id); return(file.Id); } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credential Not found"); } else if (e is GoogleApiException) { Console.WriteLine(" Failed With an Error {0}", e.Message); } else { throw; } } return(null); }
protected String MakeFolderTitle(DriveFile driveFolder) { if (driveFolder == null || IsRoot(driveFolder)) { return(GoogleDriveProviderInfo.CustomerTitle); } return(Global.ReplaceInvalidCharsAndTruncate(driveFolder.Title)); }
protected void CacheInsert(DriveFile driveEntry) { if (driveEntry != null) { CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, Key = GoogleDriveProviderInfo.ID + driveEntry.Id }, CacheNotifyAction.Remove); } }
public Google.Apis.Drive.v2.Data.File UploadFolder(Google.Apis.Drive.v2.Data.File folder) { if (!serviceStarted) { return(null); } FilesResource.InsertRequest request = driverservice.Files.Insert(folder); Google.Apis.Drive.v2.Data.File file = request.Execute(); return(file); }
protected string MakeId(DriveFile driveEntry) { var path = string.Empty; if (driveEntry != null) { path = IsRoot(driveEntry) ? "root" : driveEntry.Id; } return(MakeId(path)); }
private IEnumerable <Directory> GetAllDirectories_QueryEachLevel(string[] exclusions = null) { List <Google.Apis.Drive.v2.Data.File> folders = new List <Google.Apis.Drive.v2.Data.File>() { root }; Google.Apis.Drive.v2.Data.File[] pass = new Google.Apis.Drive.v2.Data.File[] { root }; // Rebuild folder hierarchy while (true) { string parentsQuery = string.Join(" or ", pass.Select(f => string.Format("'{0}' in parents", f.Id))); FilesResource.ListRequest request = Service.Files.List(); request.Q = string.Format("trashed = false and mimeType = '{0}' and ({1})", GoogleDriveDirectory.MimeType, parentsQuery); request.Fields = "items(id,title,parents,fileSize)"; request.MaxResults = 1000; pass = request.Execute().Items.ToArray(); folders.AddRange(pass); if (pass.Length == 0) { break; } } // Wrap all folders and rebuild parents List <GoogleDriveDirectory> directories = new List <GoogleDriveDirectory>(); foreach (Google.Apis.Drive.v2.Data.File folder in folders) { if (folder.Id == root.Id) { directories.Add(new GoogleDriveDirectory(this, null, folder)); } else { directories.Add(new GoogleDriveDirectory(this, directories.First(d => d.folder.Id == folder.Parents.Single().Id), folder)); } } // Return each directory foreach (GoogleDriveDirectory directory in directories) { if (exclusions != null && exclusions.Any(e => MatchPattern(directory.Path, e))) { continue; } yield return(directory); } }
void onFileUploaded(Google.Apis.Drive.v2.Data.File file, BackgroundWorker sendingworker) { //UploadedFiles.Add(file); UploadedFile = file; sendingworker.ReportProgress(0, new StatusHolder() { txt = "Uploading part " + Path.GetFileNameWithoutExtension(file.Title) + " of " + UpdatePackageList.Count + ": ", progress = 100 }); GoogleDriveApi.stopWaitHandle.Set(); stopWaitHandle.Set(); }
/// <summary> /// Converting DropBox Model to FileObject /// </summary> /// <param name="meta">DropBox Model</param> /// <returns>POJO FileObject</returns> //public static FileObject ConvertToFileObject(Metadata meta) //{ // string Name = meta.Name; // string UpdateAt = null; // try // { // UpdateAt = meta.ModifiedDate.ToString(); //14/02/2014 15:48:13 // } // catch // { // UpdateAt = DateTime.Now.ToString(); // } // string Id = meta.Path; // Full path // string ParentId = meta.Path; // double Size = meta.Bytes * 1.0; // FileObject.FileObjectType Type = (meta.IsDirectory ? FileObject.FileObjectType.FOLDER : FileObject.FileObjectType.FILE); // string Extension = (meta.Extension == null || "".Equals(meta.Extension)) ? "" : meta.Extension.Substring(1, meta.Extension.Length - 1); // .png // return new FileObject(Id, Name, Size, Type, Extension, UpdateAt); //} /// <summary> /// Converting GoogleDrive Model to FileObject /// </summary> /// <param name="file">GoogleDrive Model</param> /// <returns>POJO FileObject</returns> public static FileObject ConvertToFileObject(Google.Apis.Drive.v2.Data.File file) { String Id = file.Id ?? "No Id"; double Size = (file.FileSize == null ? 0.0 : file.FileSize.Value * 1.0); FileObject.FileObjectType Type = (file.MimeType.Contains("application/vnd.google-apps.folder")) ? FileObject.FileObjectType.FOLDER : (file.MimeType.Contains("application/vnd.google-apps") ? FileObject.FileObjectType.GOOGLE_DOC : FileObject.FileObjectType.FILE); string Extension = file.FileExtension ?? "No Extension"; string UpdateAt = file.ModifiedDate.ToString(); string Thumbnail = file.ThumbnailLink ?? "No Thumbnail"; string DownloadUrl = ""; try { if (file.ExportLinks != null && file.MimeType != null && file.MimeType.Contains("application/vnd.google-apps")) { DownloadUrl = file.ExportLinks[GoogleDriveManager.GoogleDocMapper[file.MimeType]]; } else { DownloadUrl = file.DownloadUrl; } } catch { System.Diagnostics.Debug.WriteLine("GoogleDocMapper Error"); System.Diagnostics.Debugger.Break(); } string MimeType = file.MimeType ?? "No MimeType"; string Name = ""; try { if (!"application/vnd.google-apps.folder".Equals(file.MimeType) && file.MimeType.Contains("application/vnd.google-apps")) { Name = file.Title + "." + GoogleDriveManager.ExtensionMapper[file.MimeType]; Extension = GoogleDriveManager.ExtensionMapper[file.MimeType]; } else { Name = file.Title; } } catch { System.Diagnostics.Debug.WriteLine(file.MimeType); System.Diagnostics.Debug.WriteLine("ExtensionMapper Error"); System.Diagnostics.Debugger.Break(); } return(new FileObject(Id, Name, Size, Type, Extension, UpdateAt, Thumbnail, DownloadUrl, MimeType)); }
public FileEntry(Google.Apis.Drive.v2.Data.File file, ImageSource thumb, string gdocWebUrl) { Modified = DateTime.Parse(file.ModifiedDate); Title = file.Title; Image = thumb; IdString = file.Id; IsFolder = GDriveStorage.IsFolder(file); GdocWebUrl = gdocWebUrl; IsGDrive = true; IsViewable = !IsFolder && (IsExtViewable(file.FileExtension) || !string.IsNullOrWhiteSpace(GdocWebUrl)); }
protected Folder ToFolder(DriveFile driveEntry) { if (driveEntry == null) { return(null); } if (driveEntry is ErrorDriveEntry) { //Return error entry return(ToErrorFolder(driveEntry as ErrorDriveEntry)); } if (driveEntry.MimeType != GoogleLoginProvider.GoogleDriveMimeTypeFolder) { return(null); } var isRoot = IsRoot(driveEntry); var folder = new Folder { ID = MakeId(driveEntry), ParentFolderID = isRoot ? null : MakeId(GetParentDriveId(driveEntry)), CreateBy = GoogleDriveProviderInfo.Owner, CreateOn = isRoot ? GoogleDriveProviderInfo.CreateOn : (driveEntry.CreatedDate.HasValue ? driveEntry.CreatedDate.Value : default(DateTime)), FolderType = FolderType.DEFAULT, ModifiedBy = GoogleDriveProviderInfo.Owner, ModifiedOn = isRoot ? GoogleDriveProviderInfo.CreateOn : (driveEntry.ModifiedDate.HasValue ? driveEntry.ModifiedDate.Value : default(DateTime)), ProviderId = GoogleDriveProviderInfo.ID, ProviderKey = GoogleDriveProviderInfo.ProviderKey, RootFolderCreator = GoogleDriveProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = GoogleDriveProviderInfo.RootFolderType, Shareable = false, Title = MakeFolderTitle(driveEntry), TotalFiles = 0, /*driveEntry.Count - childFoldersCount NOTE: Removed due to performance isssues*/ TotalSubFolders = 0, /*childFoldersCount NOTE: Removed due to performance isssues*/ }; if (folder.CreateOn != DateTime.MinValue && folder.CreateOn.Kind == DateTimeKind.Utc) { folder.CreateOn = TenantUtil.DateTimeFromUtc(folder.CreateOn); } if (folder.ModifiedOn != DateTime.MinValue && folder.ModifiedOn.Kind == DateTimeKind.Utc) { folder.ModifiedOn = TenantUtil.DateTimeFromUtc(folder.ModifiedOn); } return(folder); }
/// <summary> /// Change the file's modification timestamp. /// </summary> /// <param name="fileId">Id of file to be modified.</param> /// <param name="now">Timestamp in milliseconds.</param> /// <returns>newly modified timestamp, null otherwise.</returns> public static DateTime?DriveTouchFile(string fileId, DateTime now) { try { /* Load pre-authorized user credentials from the environment. * TODO(developer) - See https://developers.google.com/identity for * guides on implementing OAuth2 for your application. */ GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(DriveService.Scope.Drive); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Drive API Snippets" }); var fileMetadata = new Google.Apis.Drive.v2.Data.File() { ModifiedDate = DateTime.Now }; // [START_EXCLUDE silent] fileMetadata.ModifiedDate = now; // [END_EXCLUDE] var request = service.Files.Update(fileMetadata, fileId); request.SetModifiedDate = true; request.Fields = "id, modifiedDate"; var file = request.Execute(); // Prints the modified date of the file. Console.WriteLine("Modified time: " + file.ModifiedDate); return(file.ModifiedDate); } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credentials Not found {0}", e.Message); } else if (e is GoogleApiException) { Console.WriteLine("Failed with an error {0}", e.Message); } else { throw; } } return(null); }
private void Initialize() { if (Service != null) { return; } using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SmartSync.GoogleDrive.ClientSecret.json")) { Credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new SettingsDataStore()).Result; } // Create Drive API service. Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = Credential, ApplicationName = ApplicationName, }); // Locate specified path if (!IsPathValid(Path) || Path[0] != '/') { throw new Exception("The specified path is not a valid path"); } root = Service.Files.Get("root").Execute(); if (Path != "/") { string[] parts = Path.Trim('/').Split('/'); foreach (string part in parts) { FilesResource.ListRequest request = Service.Files.List(); request.Q = string.Format("'{0}' in parents and trashed = false and mimeType = '{1}' and title = '{2}'", root.Id, GoogleDriveDirectory.MimeType, part); request.Fields = "items(id,title,fileSize,mimeType)"; Google.Apis.Drive.v2.Data.File[] folders = request.Execute().Items.ToArray(); root = folders.SingleOrDefault(); if (root == null) { throw new Exception("Could not find the specified folder"); } } } }
private Dictionary <string /*spreadsheetId*/, Dictionary <string /*issueId*/, IssueEntry> > GetBCFDictionary(Document doc) { Dictionary <string, Dictionary <string, IssueEntry> > dictionary = new Dictionary <string, Dictionary <string, IssueEntry> >(); try { AbortFlag.SetAbortFlag(false); progressWindow = new ProgressWindow("Loading BCF issues and images..."); progressWindow.Show(); List <string> markupIds = bcfFileDictionary.Keys.ToList(); foreach (string markupId in markupIds) { LinkedBcfFileInfo bcfFileInfo = bcfFileDictionary[markupId]; if (null != FileManager.FindFileById(bcfFileInfo.MarkupFileId) && null != FileManager.FindFileById(bcfFileInfo.ViewpointFileId)) { Dictionary <string, IssueEntry> issueDictionary = GetBCFIssueInfo(doc, bcfFileInfo); if (AbortFlag.GetAbortFlag()) { return(new Dictionary <string, Dictionary <string, IssueEntry> >()); } if (!dictionary.ContainsKey(markupId) && issueDictionary.Count > 0) { dictionary.Add(markupId, issueDictionary); } } else { bcfFileDictionary.Remove(markupId); } } if (!string.IsNullOrEmpty(categorySheetId)) { System.IO.MemoryStream stream = BCFParser.CreateCategoryStream(categoryNames); if (null != stream) { Google.Apis.Drive.v2.Data.File file = FileManager.UpdateSpreadsheet(stream, categorySheetId, bcfProjectId); } } if (progressWindow.IsActive) { progressWindow.Close(); } } catch (Exception ex) { MessageBox.Show("Failed to get BCF dictionary.\n" + ex.Message, "Get BCF Dictionary", MessageBoxButton.OK, MessageBoxImage.Warning); } return(dictionary); }
public JsonResult svcPost(string title, string description, string mimeType, string content) { IAuthenticator authenticator = Session["authenticator"] as IAuthenticator; DriveService service = Session["service"] as DriveService; if (authenticator == null || service == null) { // redirect user to authentication } Google.Apis.Drive.v2.Data.File file = Utils.InsertResource(service, authenticator, title, description, mimeType, content); return Json(file.Id); }
public GoogleDriveItemModel(GoogleDriveProfile profile, Google.Apis.Drive.v2.Data.File file, string parentFullPath = null) : base(profile) { //string ext = file.OriginalFilename == null ? "" : profile.Path.GetExtension(file.OriginalFilename); string name = file.Title; //if (!String.IsNullOrEmpty(ext) && //OriginalFileName have ext // !file.MimeType.Equals(GoogleMimeTypeManager.FolderMimeType) && //Not folder // String.IsNullOrEmpty(profile.Path.GetExtension(name))) //Title does not have ext // name += ext; string path = parentFullPath == null ? profile.Alias : parentFullPath + "/" + name; init(profile, path, file); }
internal void init(GoogleDriveProfile profile, string path, Google.Apis.Drive.v2.Data.File f) { init(profile, path); UniqueId = f.Id; this.Metadata = f; this.IsDirectory = f.MimeType.Equals(GoogleMimeTypeManager.FolderMimeType); this.Name = profile.Path.GetFileName(path); this.Size = f.FileSize.HasValue ? f.FileSize.Value : 0; this._isRenamable = true; this.Description = f.Description; this.ImageUrl = f.ThumbnailLink; this.SourceUrl = f.DownloadUrl; this.SourceExportUrls = f.ExportLinks; this.Type = profile.MimeTypeManager.GetExportableMimeTypes(f.MimeType).FirstOrDefault(); if (!this.IsDirectory && String.IsNullOrEmpty(Profile.Path.GetExtension(this.Name))) { string extension = profile.MimeTypeManager.GetExtension(this.Type); if (!String.IsNullOrEmpty(extension)) { this.FullPath += extension; this.Label = this._name += extension; this.SourceUrl = f.ExportLinks[this.Type]; } else { extension = profile.Path.GetExtension(f.OriginalFilename); if (!String.IsNullOrEmpty(extension)) { this.FullPath += extension; this.Label = this._name += extension; } } } this.Size = f.FileSize.HasValue ? f.FileSize.Value : this.Size; this.CreationTimeUtc = f.CreatedDate.HasValue ? f.CreatedDate.Value.ToUniversalTime() : this.CreationTimeUtc; this.LastUpdateTimeUtc = f.LastViewedByMeDate.HasValue ? f.LastViewedByMeDate.Value.ToUniversalTime() : this.LastUpdateTimeUtc; if (!this.IsDirectory && System.IO.Path.GetExtension(this.Name) == "" && this.Type != null) { string extension = ShellUtils.MIMEType2Extension(this.Type); if (!String.IsNullOrEmpty(extension)) { this.Name += extension; } } }
private static void UploadFile(DriveService service) { File body = new File(); body.Title = "test image ocr - " + DateTime.Now.ToString(" - yyyyMMdd - HHmmss"); body.Description = "test image ocr - " + DateTime.Now.ToString(" - yyyyMMdd - HHmmss"); //body.MimeType = "application/vnd.ms-excel"; body.MimeType = "image/jpeg"; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes("1.jpg"); MemoryStream stream = new MemoryStream(byteArray); try { //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet"); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.photo"); request.Ocr = true; request.OcrLanguage = "vi"; request.Convert = true; request.Upload(); File imgFile = request.ResponseBody; // Copy image and paste as document var textMetadata = new File(); //textMetadata.Name = inputFile.Name; //textMetadata.Parents = new List<string> { folderId }; textMetadata.MimeType = "application/vnd.google-apps.document"; FilesResource.CopyRequest requestCopy = service.Files.Copy(textMetadata, imgFile.Id); requestCopy.Fields = "id"; requestCopy.OcrLanguage = "vi"; var textFile = requestCopy.Execute(); // Now we export document as plain text FilesResource.ExportRequest requestExport = service.Files.Export(textFile.Id, "text/plain"); string output = requestExport.Execute(); // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); Console.WriteLine(output); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
// Download file from google drive public void DownloadFile() { const string DOWNLOAD_FILE_ON_DRIVE_NAME = "My Drawing.jpg"; const string DOWNLOAD_FILE_PATH = "./"; List <Google.Apis.Drive.v2.Data.File> fileList = _service.ListRootFileAndFolder(); Google.Apis.Drive.v2.Data.File foundFile = fileList.Find(item => { return(item.Title == DOWNLOAD_FILE_ON_DRIVE_NAME); }); if (foundFile != null) { _service.DownloadFile(foundFile, DOWNLOAD_FILE_PATH); } }
protected string CreateTestBlob(string filePath) { var fileMetadata = new Google.Apis.Drive.v2.Data.File(); fileMetadata.Title = "photo.jpg"; using (var stream = new FileStream(filePath, FileMode.Open)) { var request = service.Files.Insert( fileMetadata, stream, "image/jpeg"); request.Fields = "id"; request.Upload(); var file = request.ResponseBody; return(file.Id); } }
public void Upload(Stream fileStream) { var body = new Google.Apis.Drive.v2.Data.File(); body.Title = "My document 123"; body.Description = "A test document"; body.MimeType = "text/plain"; FilesResource.InsertMediaUpload request = GoogleDriveService.Files.Insert(body, fileStream, "text/plain"); request.Upload(); Google.Apis.Drive.v2.Data.File file = request.ResponseBody; Console.WriteLine("File id: " + file.Id); Console.WriteLine("Press Enter to end this process."); Console.ReadLine(); }
/// <summary> /// Creates a new folder /// </summary> /// <returns></returns> public static string DriveCreateFolder() { try { /* Load pre-authorized user credentials from the environment. * TODO(developer) - See https://developers.google.com/identity for * guides on implementing OAuth2 for your application. */ GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(DriveService.Scope.Drive); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Drive API Snippets" }); // File metadata var fileMetadata = new Google.Apis.Drive.v2.Data.File() { Title = "Invoices", MimeType = "application/vnd.google-apps.folder" }; // Create a new folder on drive. var request = service.Files.Insert(fileMetadata); request.Fields = "id"; var file = request.Execute(); // Prints the created folder id. Console.WriteLine("Folder ID: " + file.Id); return(file.Id); } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credential Not found"); } else if (e is GoogleApiException) { Console.WriteLine("Failed to Create Folder with Error : {0}", e.Message); } else { throw; } } return(null); }
public GoogleDriveStream(GoogleDriveStorage storage, Google.Apis.Drive.v2.Data.File file) { this.storage = storage; this.file = file; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl)); request.Headers.Add("Authorization", storage.Credential.Token.TokenType + " " + storage.Credential.Token.AccessToken); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Could not retrieve file stream"); using (Stream responseStream = response.GetResponseStream()) responseStream.CopyTo(dataStream); dataStream.Seek(0, SeekOrigin.Begin); }
private async Task<string> CreateDirectory(string title, string parent = null) { File directory = null; File body = new File { Title = title, MimeType = "application/vnd.google-apps.folder" }; try { FilesResource.InsertRequest request = this.service.Files.Insert(body); directory = await request.ExecuteAsync(); } catch (Exception e) { throw new Exception(e.Message); } return directory.Id; }
public async Task<string> UploadImageToCloud(byte[] byteArrayContent, string fileName, string fileExstension, string parentPath = WebStorageConstants.Collection) { // var parentId = await this.CreateDirectory(parentPath); File body = new File { Title = fileName, // Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } } }; MemoryStream stream = new MemoryStream(byteArrayContent); try { FilesResource.InsertMediaUpload request = this.service.Files.Insert(body, stream, "image/" + fileExstension); var result = await request.UploadAsync(); return WebStorageConstants.GoogleDriveSourceLink + request.ResponseBody.Id; } catch (Exception e) { throw new Exception(e.Message); } }
/// <summary> /// Uploads File into Google Drive. /// </summary> /// <param name="fileBytes">byte[] of the file</param> /// <param name="fileNameWithExtension">File-name with extension or path ending with the filename with extension. For example: picture.jpg </param> /// <returns>File ID in Google Drive. On error returns null.</returns> public string UploadFile(byte[] fileBytes, string fileNameWithExtension) { CheckToken(ref this.credential); var body = new Google.Apis.Drive.v2.Data.File(); body.Title = fileNameWithExtension; body.Description = "File uploaded by JustMeet"; body.MimeType = GetMimeType(fileNameWithExtension); ////body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; string result = null; using (var stream = new MemoryStream(fileBytes)) { try { FilesResource.InsertMediaUpload request = this.instance.Files.Insert(body, stream, body.MimeType); ////request.Convert = true; // uncomment this line if you want files to be converted to Drive format request.Upload(); result = request.ResponseBody.Id; } catch (Exception) { result = null; } } return result; }
public GoogleDriveFile(GoogleDriveStorage storage, GoogleDriveDirectory parent, Google.Apis.Drive.v2.Data.File file) { this.storage = storage; this.parent = parent; this.file = file; }
protected static string GetParentDriveId(DriveFile driveEntry) { return driveEntry == null || driveEntry.Parents == null || driveEntry.Parents.Count == 0 ? null : driveEntry.Parents[0].Id; }
protected string MakeId(DriveFile driveEntry) { var path = string.Empty; if (driveEntry != null) { path = IsRoot(driveEntry) ? "root" : driveEntry.Id; } return MakeId(path); }
protected String MakeFolderTitle(DriveFile driveFolder) { if (driveFolder == null || IsRoot(driveFolder)) { return GoogleDriveProviderInfo.CustomerTitle; } return Global.ReplaceInvalidCharsAndTruncate(driveFolder.Title); }
public IHttpActionResult PostUploadFiles(FileBase fileBase) { try { HttpPostedFileBase theFile = fileBase.PostedFileBase; if (theFile.ContentLength != 0) { var objFile = new Dms(); var file = new File(); var buffer = new byte[theFile.ContentLength]; fileBase.PostedFileBase.InputStream.Read(buffer, 0, fileBase.PostedFileBase.ContentLength); var stream = new System.IO.MemoryStream(buffer); MemoryStream objFile1 = new MemoryStream(); file = objFile.FileUpload(ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["Clientsecret"], theFile.FileName, theFile.FileName, theFile.ContentType, stream, ConfigurationManager.ConnectionStrings["BPM"].ToString() ); if (file != null) { //ObjCPService.FileTableInsert(new CPservice.ecubeDocument //{ // ParentCode = guId, // // ParentCode = "",// replace with shipment No // DateCreated = DateTime.Now, // DocType = Request.QueryString["DocType"], // DocName = Request.QueryString["DocDesc"], // DocumentURL = file.DownloadUrl, // DocReferenceID = file.Id, // FileName = file.OriginalFilename.Substring(file.OriginalFilename.LastIndexOf("\\") + 1), // //FileContentBytes = buffer, // FileExtension = file.FileExtension, // UploadedBy = Session["EmailId"].ToString(), //Session["UserId"].ToString(), // PublicViewable = "Y", // ParentSystem = "CP",//eCube // ParentSource = "Shipment", // ContentType = file.FileExtension, // SizeInKB = Convert.ToInt64(Math.Round(ConvertBytesToMegabytes(Convert.ToInt64(file.FileSize)), 4)) //}); var documents = new eDrive_Document { DocCode = "", FileName = file.OriginalFilename, FileExtension = file.FileExtension, SizeinKb = Convert.ToInt64(Math.Round(ConvertBytesToMegabytes(Convert.ToInt64(file.FileSize)), 4)), ContentType = file.FileExtension, IsPublic = true, IsAuto = true, IsDeleted = false, ParentSystem = fileBase.ParentSystem, ParentSource = fileBase.ParentSource, ParentCode= "Parent Code", IsQuarantine=true, GoogleReferenceId = file.Id, GoogleURL = file.DownloadUrl, CreatedBy = "Admin", CreatedDate=DateTime.Now, ModifiedBy="Admin", DateModified = DateTime.Now }; _db.eDrive_Document.Add(documents); _db.SaveChanges(); } } return Ok(); } catch (Exception e) { throw e; } }
protected Folder ToFolder(DriveFile driveEntry) { if (driveEntry == null) return null; if (driveEntry is ErrorDriveEntry) { //Return error entry return ToErrorFolder(driveEntry as ErrorDriveEntry); } if (driveEntry.MimeType != GoogleDriveStorage.GoogleFolderMimeType) { return null; } var isRoot = IsRoot(driveEntry); var folder = new Folder { ID = MakeId(driveEntry), ParentFolderID = isRoot ? null : MakeId(GetParentDriveId(driveEntry)), CreateBy = GoogleDriveProviderInfo.Owner, CreateOn = isRoot ? GoogleDriveProviderInfo.CreateOn : (driveEntry.CreatedDate.HasValue ? driveEntry.CreatedDate.Value : default(DateTime)), FolderType = FolderType.DEFAULT, ModifiedBy = GoogleDriveProviderInfo.Owner, ModifiedOn = isRoot ? GoogleDriveProviderInfo.CreateOn : (driveEntry.ModifiedDate.HasValue ? driveEntry.ModifiedDate.Value : default(DateTime)), ProviderId = GoogleDriveProviderInfo.ID, ProviderKey = GoogleDriveProviderInfo.ProviderKey, RootFolderCreator = GoogleDriveProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = GoogleDriveProviderInfo.RootFolderType, Shareable = false, Title = MakeFolderTitle(driveEntry), TotalFiles = 0, /*driveEntry.Count - childFoldersCount NOTE: Removed due to performance isssues*/ TotalSubFolders = 0, /*childFoldersCount NOTE: Removed due to performance isssues*/ }; if (folder.CreateOn != DateTime.MinValue && folder.CreateOn.Kind == DateTimeKind.Utc) folder.CreateOn = TenantUtil.DateTimeFromUtc(folder.CreateOn); if (folder.ModifiedOn != DateTime.MinValue && folder.ModifiedOn.Kind == DateTimeKind.Utc) folder.ModifiedOn = TenantUtil.DateTimeFromUtc(folder.ModifiedOn); return folder; }
/// <summary> /// Create a new file and return it. /// </summary> public static Google.Apis.Drive.v2.Data.File InsertResource(Google.Apis.Drive.v2.DriveService service, IAuthenticator auth, String title, String description, String mimeType, String content) { // File's metadata. Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); body.Title = title; body.Description = description; body.MimeType = mimeType; byte[] byteArray = Encoding.ASCII.GetBytes(content); MemoryStream stream = new MemoryStream(byteArray); Google.Apis.Drive.v2.FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); return request.ResponseBody; }
private static bool IsDriveFolder(DriveFile driveFolder) { return driveFolder != null && driveFolder.MimeType == GoogleDriveStorage.GoogleFolderMimeType; }
public File ToFile(DriveFile driveFile) { if (driveFile == null) return null; if (driveFile is ErrorDriveEntry) { //Return error entry return ToErrorFile(driveFile as ErrorDriveEntry); } return new File { ID = MakeId(driveFile.Id), Access = FileShare.None, ContentLength = driveFile.FileSize.HasValue ? (long)driveFile.FileSize : 0, CreateBy = GoogleDriveProviderInfo.Owner, CreateOn = driveFile.CreatedDate.HasValue ? TenantUtil.DateTimeFromUtc(driveFile.CreatedDate.Value) : default(DateTime), FileStatus = FileStatus.None, FolderID = MakeId(GetParentDriveId(driveFile)), ModifiedBy = GoogleDriveProviderInfo.Owner, ModifiedOn = driveFile.ModifiedDate.HasValue ? TenantUtil.DateTimeFromUtc(driveFile.ModifiedDate.Value) : default(DateTime), NativeAccessor = driveFile, ProviderId = GoogleDriveProviderInfo.ID, ProviderKey = GoogleDriveProviderInfo.ProviderKey, Title = MakeFileTitle(driveFile), RootFolderId = MakeId(), RootFolderType = GoogleDriveProviderInfo.RootFolderType, RootFolderCreator = GoogleDriveProviderInfo.Owner, SharedByMe = false, Version = 1 }; }
protected void CacheInsert(DriveFile driveEntry) { CacheEntry.Add(GoogleDriveProviderInfo.ID + driveEntry.Id, driveEntry); }
public GDriveFile(Google.Apis.Drive.v2.Data.File item) { this.item = item; }
protected String MakeFileTitle(DriveFile driveFile) { var ext = string.Empty; if (driveFile == null || string.IsNullOrEmpty(driveFile.Title)) { return GoogleDriveProviderInfo.ProviderKey; } Tuple<string, string> mimeData; if (GoogleDriveStorage.GoogleFilesMimeTypes.TryGetValue(driveFile.MimeType, out mimeData)) { ext = mimeData.Item1; } return Global.ReplaceInvalidCharsAndTruncate(driveFile.Title + ext); }
protected static bool IsRoot(DriveFile driveFolder) { return IsDriveFolder(driveFolder) && GetParentDriveId(driveFolder) == null; }
public File GetNewFile(string title, string target) { char separator = '\\'; //System.IO.Path.DirectorySeparatorChar; string parent = target.Substring(0, target.IndexOf(separator)); Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File(); file.Title = title; file.Description = "Google Drive Downloader"; file.MimeType = GetMimeType(title); file.Parents = new List<Google.Apis.Drive.v2.Data.ParentReference>() { new Google.Apis.Drive.v2.Data.ParentReference() { Id = parent } }; return new GDriveFile(file); }