/// <summary> /// Auth and get all files in AppData. /// </summary> IEnumerator InitGoogleDrive() { initInProgress = true; drive = new GoogleDrive(); drive.ClientID = "897584417662-rnkgkl5tlpnsau7c4oc0g2jp08cpluom.apps.googleusercontent.com"; drive.ClientSecret = "tGNLbYnrdRO2hdFmwJAo5Fbt"; var authorization = drive.Authorize(); yield return StartCoroutine(authorization); if (authorization.Current is Exception) { Debug.LogWarning(authorization.Current as Exception); goto finish; } else Debug.Log("User Account: " + drive.UserAccount); // Get all files in AppData folder and view text file. { var listFiles = drive.ListFiles(drive.AppData); yield return StartCoroutine(listFiles); var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles); if (files != null) { foreach (var file in files) { Debug.Log(file); if (file.Title.EndsWith(".txt")) { var download = drive.DownloadFile(file); yield return StartCoroutine(download); var data = GoogleDrive.GetResult<byte[]>(download); Debug.Log(System.Text.Encoding.UTF8.GetString(data)); } } } else { Debug.LogError(listFiles.Current); } } finish: initInProgress = false; }
/// <summary> /// Auth and get all files in AppData. /// </summary> IEnumerator InitGoogleDrive() { initInProgress = true; drive = new GoogleDrive(); drive.ClientID = "251952116687-bl6cbb0n9veq5ovirpk5n99pjlgtf16g.apps.googleusercontent.com"; drive.ClientSecret = "z65O11Za6aB74a7r21_TbtFL"; var authorization = drive.Authorize(); yield return StartCoroutine(authorization); if (authorization.Current is Exception) { Debug.LogWarning(authorization.Current as Exception); goto finish; } else Debug.Log("User Account: " + drive.UserAccount); // Get all files in AppData folder and view text file. { //var listFiles = drive.ListFiles(drive.AppData); //var listFiles = drive.ListAllFiles(); var listFiles = drive.ListFolders(""); yield return StartCoroutine(listFiles); var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles); if (files != null) { foreach (var file in files) { Debug.Log(file); if (file.Title.EndsWith(".txt")) { var download = drive.DownloadFile(file); yield return StartCoroutine(download); var data = GoogleDrive.GetResult<byte[]>(download); Debug.Log(System.Text.Encoding.UTF8.GetString(data)); } } } else { Debug.LogError(listFiles.Current); } } finish: initInProgress = false; }
internal IConnector CurrentConnector(Member member) { if (member == null || member.StorageAccesses.Count == 0) { return(null); } IConnector connector; switch (member.StorageAccessType) { case StorageProviderType.Dropbox: connector = new DropboxConnector(DataRepository); break; case StorageProviderType.GoogleDrive: connector = new GoogleDrive(DataRepository); break; case StorageProviderType.OneDrive: connector = new Connector.OneDrive.OneDrive(DataRepository); break; case StorageProviderType.LocalDrive: connector = new Connector.LocalDrive.LocalDrive(DataRepository, string.Format("{0}://{1}", Request.RequestUri.Scheme, Request.RequestUri.Authority), member.Alias); break; default: throw new InvalidEnumArgumentException(string.Format("Der Connector {0} ist unbekannt", member.StorageAccessType)); } var access = member.StorageAccesses.First(s => s.Type == member.StorageAccessType); connector.RedirectUrl = RedirectUrl; connector.CurrentMember = member; connector.Connect(access); return(connector); }
/// <summary> /// Upload a screenshot to the root folder. /// </summary> IEnumerator UploadScreenshot() { if (drive == null || !drive.IsAuthorized || uploadScreenshotInProgress) { yield break; } uploadScreenshotInProgress = true; yield return(new WaitForEndOfFrame()); var tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); tex.Apply(); var png = tex.EncodeToPNG(); GameObject.Destroy(tex); tex = null; if (file == null) { var upload = drive.UploadFile("my_screen.png", "image/png", png); yield return(StartCoroutine(upload)); file = GoogleDrive.GetResult <GoogleDrive.File>(upload); } else { var upload = drive.UploadFile(file, png); yield return(StartCoroutine(upload)); file = GoogleDrive.GetResult <GoogleDrive.File>(upload); } uploadScreenshotInProgress = false; }
/// <summary> /// Saves a zip of the user's images to GoogleDrive, if configured. /// </summary> /// <exception cref="MyFlightbookException"></exception> /// <param name="activeBrand">The brand to use. Current brand is used if null.</param> /// <param name="gd">The GoogleDrive object to use - Must be initialized and refreshed!</param> /// <returns>True for success</returns> public async Task <GoogleDriveResultDictionary> BackupImagesToGoogleDrive(GoogleDrive gd, Brand activeBrand = null) { if (activeBrand == null) { activeBrand = Branding.CurrentBrand; } if (gd == null) { throw new ArgumentNullException(nameof(gd)); } if (User.GoogleDriveAccessToken == null) { throw new MyFlightbookException(Resources.Profile.errNotConfiguredGoogleDrive); } using (MemoryStream ms = new MemoryStream()) { WriteZipOfImagesToStream(ms, activeBrand); return(await gd.PutFile(ms, BackupImagesFilename(activeBrand, true), "application/zip").ConfigureAwait(true)); } }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="import">False is copy</param> void SameAccountCloud(TransferItem item, bool import = true) { switch (item.From.node.GetRoot.RootType.Type) { case CloudType.GoogleDrive: Drivev2_File f = GoogleDrive.MoveItem(item.From.node, item.To.node, null, true); foreach (var p in f.parents) { if (p.id == item.To.node.Parent.Info.ID) { item.status = StatusTransfer.Done; } else { item.status = StatusTransfer.Error; } } break; default: throw new Exception("SameAccountCloud not support now."); } }
/// <summary> /// Saves a zip of the user's images to GoogleDrive, if configured. /// </summary> /// <exception cref="MyFlightbookException"></exception> /// <param name="activeBrand">The brand to use. Current brand is used if null.</param> /// <param name="gd">The GoogleDrive object to use - Must be initialized and refreshed!</param> /// <returns>True for success</returns> public async Task <GoogleDriveResultDictionary> BackupImagesToGoogleDrive(GoogleDrive gd, Brand activeBrand = null) { if (activeBrand == null) { activeBrand = Branding.CurrentBrand; } if (gd == null) { throw new ArgumentNullException(nameof(gd)); } if (User.GoogleDriveAccessToken == null) { throw new MyFlightbookException(Resources.Profile.errNotConfiguredGoogleDrive); } using (FileStream fs = new FileStream(Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite, FileShare.None, Int16.MaxValue, FileOptions.DeleteOnClose)) { WriteZipOfImagesToStream(fs, activeBrand); return(await gd.PutFile(fs, BackupImagesFilename(activeBrand, true), "application/zip").ConfigureAwait(true)); } }
void AtualizaVersao() { try { using (new Carregando("Baixando Atualizações...")) { Directory.Delete($"{mainPath}\\Update", true); Directory.CreateDirectory(mainPath + "\\Update"); GoogleDrive.Download("Update.zip", $"{mainPath}\\Update\\Update.zip"); ExtrairArquivoZip($"{mainPath}\\Update\\Update.zip", $"{mainPath}\\Update\\"); File.Delete($"{mainPath}\\Update\\Update.zip"); Process.Start($"{mainPath}\\Update\\Update.exe"); //Process.GetProcesses("AgendaMais.exe"); Process.GetCurrentProcess().Kill(); } } catch { MessageBox.Show("Não consegui fazer o Download da nova versão! Vou tentar novamente mais tarde ok?"); } }
void AlterarSenha(string login) { try { using (new Carregando("Alterando Senha...")) { string[] arquivo = File.ReadAllLines($"{mainPath}\\BD\\{login}"); arquivo[1] = "senha=" + txtNovaSenha.Text; File.WriteAllLines($"{mainPath}\\BD\\{login}", arquivo); GoogleDrive.DeletarItem(login); GoogleDrive.Upload($"{mainPath}\\BD\\{login}"); } MessageBox.Show("Senha alterada com sucesso!", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { throw; } }
public void ExecuteBackup() { var backup = new BackupMysql(_backupConfigurations.ConnectionString); var folderPath = $"{Path.GetTempPath()}{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}"; var backupFile = $"{folderPath}\\backup.sql"; Directory.CreateDirectory(folderPath); string ret = backup.BackupDatabase(backupFile); if (!string.IsNullOrWhiteSpace(ret)) { _logger.LogError(new BackupException(ret), ret); } var zipPath = folderPath + ".zip"; ZipFile.CreateFromDirectory(folderPath, zipPath); var googleDrive = new GoogleDrive(_logger, _configuration); Task.Delay(1000).Wait(); googleDrive.UploadZipedFile(zipPath); }
/// <summary> /// <para>Update 'my_text.txt' in the root folder.</para> /// <para>The file has json data.</para> /// </summary> IEnumerator UploadText() { if (drive == null || !drive.IsAuthorized || uploadTextInProgress) { yield break; } uploadTextInProgress = true; // Get 'my_text.txt'. var list = drive.ListFilesByQueary("title = 'my_text.txt'"); yield return(StartCoroutine(list)); GoogleDrive.File file; Dictionary <string, object> data; var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(list); if (files == null || files.Count > 0) { // Found! file = files[0]; // Download file data. var download = drive.DownloadFile(file); yield return(StartCoroutine(download)); var bytes = GoogleDrive.GetResult <byte[]>(download); try { // Data is json format. var reader = new JsonFx.Json.JsonReader(Encoding.UTF8.GetString(bytes)); data = reader.Deserialize <Dictionary <string, object> >(); } catch (Exception e) { Debug.LogWarning(e); data = new Dictionary <string, object>(); } } else { // Make a new file. file = new GoogleDrive.File(new Dictionary <string, object> { { "title", "my_text.txt" }, { "mimeType", "text/plain" }, { "description", "test" } }); data = new Dictionary <string, object>(); } // Update file data. data["date"] = DateTime.Now.ToString(); if (data.ContainsKey("count")) { data["count"] = (int)data["count"] + 1; } else { data["count"] = 0; } // And uploading... { var bytes = Encoding.UTF8.GetBytes(JsonFx.Json.JsonWriter.Serialize(data)); var upload = drive.UploadFile(file, bytes); yield return(StartCoroutine(upload)); if (!(upload.Current is Exception)) { Debug.Log("Upload complete!"); } } uploadTextInProgress = false; }
private async void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { Text = e.Url.AbsoluteUri; var path = e.Url.AbsoluteUri; if (path.StartsWith(ConfigAPI.redirect_uri)) { if (string.IsNullOrEmpty(ConfigAPI.client_secret)) { // secret key exists. // get access token via remote. return; } else { // secret key exists. // get access token from local. const string code_str = "?code="; var i = path.IndexOf(code_str); if (i < 0) { return; } var j = path.IndexOf('&', i); var code = (j < 0) ? path.Substring(i + code_str.Length) : path.Substring(i + code_str.Length, j - (i + code_str.Length)); key = await GetAccessToken(code, ct_soruce.Token); if (key != null && key.access_token != "") { server.Refresh_Token = key.refresh_token; webBrowser1.DocumentText = "<html><body>Login success</body></html>"; timer1.Enabled = true; } } } if (path.StartsWith(ConfigAPI.App_GetToken)) { try { var body = webBrowser1.DocumentText; var i = body.IndexOf("{"); var j = body.IndexOf("}"); if (i < 0 || j < 0) { return; } key = GoogleDrive.ParseAuthResponse(body.Substring(i, j - i)); if (key.refresh_token == null) { GoogleDrive.RevokeToken(key).Wait(); webBrowser1.DocumentText = "<html><body>Login failed. please retry</body></html>"; key.access_token = null; return; } // Save refresh_token server.Refresh_Token = key.refresh_token; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } if (key != null && key.access_token != "") { webBrowser1.DocumentText = "<html><body>Login success</body></html>"; timer1.Enabled = true; } } }
public bool Upload(GoogleDrive googleDrive) { bool result = false; tokenSource = new CancellationTokenSource(); manualReset = new ManualResetEvent(true); finIndicator = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(async x => { this.IsAlive = true; try { if (this.ID.IsNullOrEmptyOrWhiltSpace() || this.mDatabase is null) { result = await googleDrive.UploadResumableAsync(this.FullPath, this.RemotePath, tokenSource.Token, this.manualReset) != null; } else { string uri = this.mDatabase.GetFileUploadID(this.ID); string getID(bool force) { if (string.IsNullOrWhiteSpace(uri) || force) { uri = googleDrive.GenerateUploadID(this.FullPath, this.RemotePath); this.mDatabase.SetUploadStatus(this.ID, uri); } return(uri); } var id = await googleDrive.UploadResumableAsync(this.FullPath, getID, tokenSource.Token, this.manualReset); if (!id.IsNullOrEmptyOrWhiltSpace()) { this.mDatabase.SetUploadStatus(this.ID, id, true); result = true; } else { result = false; } } } catch (Exception ex) { ex.Message.ErrorLognConsole(); return; } finally { this.IsAlive = false; finIndicator.Set(); } }); try { finIndicator.WaitOne(); } finally { tokenSource.Dispose(); manualReset.Dispose(); GC.Collect(); } return(result); }
//public Storage(string[] Albumname) //{ // settingStore = new JsonStore<Settings>(dbPath: HttpRuntime.AppDomainAppPath); // albumStore = new JsonStore<Albums>(dbPath: HttpRuntime.AppDomainAppPath); // AlbumList.AddRange(Albumname); //} void Refresh() { var store = new BiggyList<Albums>(albumStore); List<Albums> albumContent = new List<Albums>(); var drive = new GoogleDrive(); if (AlbumList.Count > 0) { for (int i = 0; i < AlbumList.Count; i++) { string AlbumId = drive.GetFolderID(AlbumList[i]); var contents = drive.ListFolderContent(AlbumId); foreach (var image in contents) { Albums album = new Albums(); album.Id = image.Id; album.Title = image.Title; album.AlbumName = AlbumList[i]; album.ThumbnailLink = image.ThumbnailLink; album.DownloadURL = image.DownloadUrl; albumContent.Add(album); } } store.Add(albumContent); } }
static void Main(string[] args) { Console.WriteLine("Application start"); try { LogUtils.Log("*********** APP STARTED **********"); LogUtils.Log("Step # 1 : Unmapping previous drive."); string UserLinks = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Links\\Cloud Drive.lnk"); MirrorUtils.UnmapDrive(ApplicationSettings.MappedDriveLetter); if (!Directory.Exists(ApplicationSettings.MappedFolder)) { Directory.CreateDirectory(ApplicationSettings.MappedFolder); } ResourceUtils.SetFolderIcon(ApplicationSettings.MappedFolder, "Cloude Plus Drive"); LogUtils.Log("Removing favoriates...."); if (File.Exists(UserLinks)) { File.Delete(UserLinks); } LogUtils.Log("Adding folder into favoriates"); try { MirrorUtils.CreateShortcut(ApplicationSettings.MappedFolder, UserLinks, "", "", "", Path.GetDirectoryName(UserLinks)); } catch { } // this is comment by masroor LogUtils.Log(string.Format("Mapping drive {0} at {1}", ApplicationSettings.MappedDriveLetter, ApplicationSettings.MappedFolder)); MirrorUtils.MapDrive(ApplicationSettings.MappedDriveLetter, ApplicationSettings.MappedFolder); MirrorUtils.SetDriveIcon(ApplicationSettings.MappedDriveLetter); LogUtils.Log("drive mapped"); MirrorUtils.DisplayDriveInfo(); ResourceUtils.RecreateAllExecutableResources(); ICloudService dropbox = new DropBox(); ICloudService googledrive = new GoogleDrive(); ICloudService copydrive = new CopyDrive(); ICloudService onedrive = new OneDrive(); ICloudService amazon = new AmazonDrive(); dropbox.AvaiableMemoryInBytes = DirectoryUtils.SizeInBytes(0, 2, 512, 0, 0); googledrive.AvaiableMemoryInBytes = DirectoryUtils.SizeInBytes(0, 15, 0, 0, 0); copydrive.AvaiableMemoryInBytes = DirectoryUtils.SizeInBytes(0, 15, 0, 0, 0); onedrive.AvaiableMemoryInBytes = DirectoryUtils.SizeInBytes(0, 7, 0, 0, 0); amazon.AvaiableMemoryInBytes = DirectoryUtils.SizeInBytes(0, 5, 0, 0, 0); LogUtils.Log("Unmapping drives..."); LogUtils.Log(string.Format("Unmapping Dropbox: {0}", MirrorUtils.UnmapFolder(dropbox.ApplicationName))); LogUtils.Log(string.Format("Unmapping Google Drive: {0}", MirrorUtils.UnmapFolder(googledrive.ApplicationName))); LogUtils.Log(string.Format("Unmapping Copy Drive: {0}", MirrorUtils.UnmapFolder(copydrive.ApplicationName))); LogUtils.Log(string.Format("Unmapping One Drive: {0}", MirrorUtils.UnmapFolder(onedrive.ApplicationName))); LogUtils.Log(string.Format("Unmapping Amazon: {0}", MirrorUtils.UnmapFolder(amazon.ApplicationName))); LogUtils.Log(string.Format("Dropbox installed status: {0}", dropbox.IsInstalled)); LogUtils.Log(string.Format("Dropbox client folder: {0}", dropbox.ClientFolder)); LogUtils.Log(string.Format("Dropbox folder status: {0}", dropbox.ClientFolderExists ? "Exists" : "Not Exists")); LogUtils.Log(string.Format("Dropbox Drive Available Space: {0}", DirectoryUtils.PretifyBytes(dropbox.AvaiableMemoryInBytes))); LogUtils.Log(string.Format("Dropbox Drive Used Space: {0}", DirectoryUtils.PretifyBytes(dropbox.UsedMemoryInBytes))); LogUtils.Log(string.Format("Dropbox Drive mapping : {0}", MirrorUtils.MapFolder(dropbox))); LogUtils.Log("---------------------------------------------------------------"); LogUtils.Log(string.Format("Amazon Drive installed status: {0}", amazon.IsInstalled)); LogUtils.Log(string.Format("Amazon client folder: {0}", amazon.ClientFolder)); LogUtils.Log(string.Format("Amazon folder status: {0}", amazon.ClientFolderExists ? "Exists" : "Not Exists")); LogUtils.Log(string.Format("Amazon Drive Available Space: {0}", DirectoryUtils.PretifyBytes(amazon.AvaiableMemoryInBytes))); LogUtils.Log(string.Format("Amazon Drive Used Space: {0}", DirectoryUtils.PretifyBytes(amazon.UsedMemoryInBytes))); LogUtils.Log(string.Format("Amazon Drive mapping : {0}", MirrorUtils.MapFolder(amazon))); LogUtils.Log("---------------------------------------------------------------"); LogUtils.Log(string.Format("One Drive installed status: {0}", onedrive.IsInstalled)); LogUtils.Log(string.Format("One Drive Client Folder: {0}", onedrive.ClientFolder)); LogUtils.Log(string.Format("One Drive folder status: {0}", onedrive.ClientFolderExists ? "Exists" : "Not Exists")); LogUtils.Log(string.Format("One Drive Available Size: {0}", DirectoryUtils.PretifyBytes(onedrive.AvaiableMemoryInBytes))); LogUtils.Log(string.Format("One Drive Used Size: {0}", DirectoryUtils.PretifyBytes(onedrive.UsedMemoryInBytes))); LogUtils.Log(string.Format("One Drive mapping : {0}", MirrorUtils.MapFolder(onedrive))); LogUtils.Log("---------------------------------------------------------------"); LogUtils.Log(string.Format("Copy Drive installed status: {0}", copydrive.IsInstalled)); LogUtils.Log(string.Format("Copy Drive Client Folder: {0}", copydrive.ClientFolder)); LogUtils.Log(string.Format("Copy Drive folder status: {0}", copydrive.ClientFolderExists ? "Exists" : "Not Exists")); LogUtils.Log(string.Format("Copy Drive Available Size: {0}", DirectoryUtils.PretifyBytes(copydrive.AvaiableMemoryInBytes))); LogUtils.Log(string.Format("Copy Drive Used Size: {0}", DirectoryUtils.PretifyBytes(copydrive.UsedMemoryInBytes))); LogUtils.Log(string.Format("Copy Drive mapping : {0}", MirrorUtils.MapFolder(copydrive))); LogUtils.Log("---------------------------------------------------------------"); LogUtils.Log(string.Format("Google Drive installed status: {0}", googledrive.IsInstalled)); LogUtils.Log(string.Format("Google Drive Client Folder: {0}", googledrive.ClientFolder)); LogUtils.Log(string.Format("Google Drive folder status: {0}", googledrive.ClientFolderExists ? "Exists" : "Not Exists")); LogUtils.Log(string.Format("Google Drive Available Size: {0}", DirectoryUtils.PretifyBytes(googledrive.AvaiableMemoryInBytes))); LogUtils.Log(string.Format("Google Drive Used Size: {0}", DirectoryUtils.PretifyBytes(googledrive.UsedMemoryInBytes))); LogUtils.Log(string.Format("Google Drive mapping : {0}", MirrorUtils.MapFolder(googledrive))); } catch (Exception ex) { LogUtils.LogE(ex); } Console.WriteLine("Press any key to end"); Console.Read(); }
private UploadResult UploadFile(string ssPath) { FileUploader fileUploader = null; switch (Program.Settings.ImageFileUploaderType) { case FileDestination.Dropbox: fileUploader = new Dropbox(Program.UploadersConfig.DropboxOAuth2Info, Program.UploadersConfig.DropboxAccountInfo) { UploadPath = NameParser.Parse(NameParserType.URL, Dropbox.TidyUploadPath(Program.UploadersConfig.DropboxUploadPath)), AutoCreateShareableLink = Program.UploadersConfig.DropboxAutoCreateShareableLink, ShareURLType = Program.UploadersConfig.DropboxURLType }; break; case FileDestination.Copy: fileUploader = new Copy(Program.UploadersConfig.CopyOAuthInfo, Program.UploadersConfig.CopyAccountInfo) { UploadPath = NameParser.Parse(NameParserType.URL, Copy.TidyUploadPath(Program.UploadersConfig.CopyUploadPath)), URLType = Program.UploadersConfig.CopyURLType }; break; case FileDestination.GoogleDrive: fileUploader = new GoogleDrive(Program.UploadersConfig.GoogleDriveOAuth2Info) { IsPublic = Program.UploadersConfig.GoogleDriveIsPublic, FolderID = Program.UploadersConfig.GoogleDriveUseFolder ? Program.UploadersConfig.GoogleDriveFolderID : null }; break; case FileDestination.RapidShare: fileUploader = new RapidShare(Program.UploadersConfig.RapidShareUsername, Program.UploadersConfig.RapidSharePassword, Program.UploadersConfig.RapidShareFolderID); break; case FileDestination.SendSpace: fileUploader = new SendSpace(APIKeys.SendSpaceKey); switch (Program.UploadersConfig.SendSpaceAccountType) { case AccountType.Anonymous: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey); break; case AccountType.User: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey, Program.UploadersConfig.SendSpaceUsername, Program.UploadersConfig.SendSpacePassword); break; } break; case FileDestination.Minus: fileUploader = new Minus(Program.UploadersConfig.MinusConfig, Program.UploadersConfig.MinusOAuth2Info); break; case FileDestination.Box: fileUploader = new Box(Program.UploadersConfig.BoxOAuth2Info) { FolderID = Program.UploadersConfig.BoxSelectedFolder.id, Share = Program.UploadersConfig.BoxShare }; break; case FileDestination.Gfycat: fileUploader = new GfycatUploader(); break; case FileDestination.Ge_tt: fileUploader = new Ge_tt(APIKeys.Ge_ttKey) { AccessToken = Program.UploadersConfig.Ge_ttLogin.AccessToken }; break; case FileDestination.Localhostr: fileUploader = new Hostr(Program.UploadersConfig.LocalhostrEmail, Program.UploadersConfig.LocalhostrPassword) { DirectURL = Program.UploadersConfig.LocalhostrDirectURL }; break; case FileDestination.CustomFileUploader: if (Program.UploadersConfig.CustomUploadersList.IsValidIndex(Program.UploadersConfig.CustomFileUploaderSelected)) { fileUploader = new CustomFileUploader(Program.UploadersConfig.CustomUploadersList[Program.UploadersConfig.CustomFileUploaderSelected]); } break; case FileDestination.FTP: FTPAccount account = Program.UploadersConfig.FTPAccountList.ReturnIfValidIndex(Program.UploadersConfig.FTPSelectedImage); if (account != null) { if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS) { fileUploader = new FTP(account); } else if (account.Protocol == FTPProtocol.SFTP) { fileUploader = new SFTP(account); } } break; case FileDestination.SharedFolder: int idLocalhost = Program.UploadersConfig.LocalhostSelectedImages; if (Program.UploadersConfig.LocalhostAccountList.IsValidIndex(idLocalhost)) { fileUploader = new SharedFolderUploader(Program.UploadersConfig.LocalhostAccountList[idLocalhost]); } break; case FileDestination.Email: using (EmailForm emailForm = new EmailForm(Program.UploadersConfig.EmailRememberLastTo ? Program.UploadersConfig.EmailLastTo : string.Empty, Program.UploadersConfig.EmailDefaultSubject, Program.UploadersConfig.EmailDefaultBody)) { emailForm.Icon = ShareXResources.Icon; if (emailForm.ShowDialog() == DialogResult.OK) { if (Program.UploadersConfig.EmailRememberLastTo) { Program.UploadersConfig.EmailLastTo = emailForm.ToEmail; } fileUploader = new Email { SmtpServer = Program.UploadersConfig.EmailSmtpServer, SmtpPort = Program.UploadersConfig.EmailSmtpPort, FromEmail = Program.UploadersConfig.EmailFrom, Password = Program.UploadersConfig.EmailPassword, ToEmail = emailForm.ToEmail, Subject = emailForm.Subject, Body = emailForm.Body }; } } break; case FileDestination.Jira: fileUploader = new Jira(Program.UploadersConfig.JiraHost, Program.UploadersConfig.JiraOAuthInfo, Program.UploadersConfig.JiraIssuePrefix); break; case FileDestination.Mega: fileUploader = new Mega(Program.UploadersConfig.MegaAuthInfos, Program.UploadersConfig.MegaParentNodeId); break; case FileDestination.AmazonS3: fileUploader = new AmazonS3(Program.UploadersConfig.AmazonS3Settings); break; case FileDestination.OwnCloud: fileUploader = new OwnCloud(Program.UploadersConfig.OwnCloudHost, Program.UploadersConfig.OwnCloudUsername, Program.UploadersConfig.OwnCloudPassword) { Path = Program.UploadersConfig.OwnCloudPath, CreateShare = Program.UploadersConfig.OwnCloudCreateShare, DirectLink = Program.UploadersConfig.OwnCloudDirectLink, IgnoreInvalidCert = Program.UploadersConfig.OwnCloudIgnoreInvalidCert }; break; case FileDestination.Pushbullet: fileUploader = new Pushbullet(Program.UploadersConfig.PushbulletSettings); break; case FileDestination.MediaCrush: fileUploader = new MediaCrushUploader() { DirectLink = Program.UploadersConfig.MediaCrushDirectLink }; break; case FileDestination.MediaFire: fileUploader = new MediaFire(APIKeys.MediaFireAppId, APIKeys.MediaFireApiKey, Program.UploadersConfig.MediaFireUsername, Program.UploadersConfig.MediaFirePassword) { UploadPath = NameParser.Parse(NameParserType.URL, Program.UploadersConfig.MediaFirePath), UseLongLink = Program.UploadersConfig.MediaFireUseLongLink }; break; case FileDestination.Pomf: fileUploader = new Pomf(); break; } if (fileUploader != null) { ReportProgress(ProgressType.UPDATE_STATUSBAR_DEBUG, string.Format("Uploading {0}.", Path.GetFileName(ssPath))); return(fileUploader.Upload(ssPath)); } return(null); }
void Transfer(TransferItem item) { #if DEBUG Console.WriteLine("Transfer items:" + item.From.node.GetFullPathString()); #endif int buffer_length = 32; //default int.TryParse(AppSetting.settings.GetSettingsAsString(SettingsKey.BufferSize), out buffer_length); //get buffer_length from setting item.buffer = item.From.node.GetRoot.NodeType.Type == CloudType.Mega ? new byte[buffer_length * 2048] : new byte[buffer_length * 1024]; //create buffer ExplorerNode rootnodeto = item.To.node.GetRoot; item.byteread = 0; //this.group.items[x].UploadID = "";//resume item.SizeWasTransfer = item.OldTransfer = item.SaveSizeTransferSuccess; //resume item.ErrorMsg = ""; //clear error item.TimeStamp = CurrentMillis.Millis; if (GroupData.status != StatusTransfer.Running) { return; } switch (rootnodeto.NodeType.Type) { case CloudType.LocalDisk: #region LocalDisk ItemsTransferWork.Add(new TransferBytes(item, this)); return; #endregion case CloudType.Dropbox: #region Dropbox int chunksizedb = 25; //default 25Mb int.TryParse(AppSetting.settings.GetSettingsAsString(SettingsKey.Dropbox_ChunksSize), out chunksizedb); item.ChunkUploadSize = chunksizedb * 1024 * 1024; DropboxRequestAPIv2 DropboxClient = Dropbox.GetAPIv2(rootnodeto.NodeType.Email); if (string.IsNullOrEmpty(item.UploadID)) //create upload id { item.byteread = item.From.stream.Read(item.buffer, 0, item.buffer.Length); IDropbox_Request_UploadSessionAppend session = DropboxClient.upload_session_start(item.buffer, item.byteread); item.UploadID = session.session_id; item.SizeWasTransfer += item.byteread; } ItemsTransferWork.Add(new TransferBytes(item, this, DropboxClient)); return; #endregion case CloudType.GoogleDrive: #region GoogleDrive DriveAPIHttprequestv2 gdclient = GoogleDrive.GetAPIv2(rootnodeto.NodeType.Email); GoogleDrive.CreateFolder(item.To.node.Parent); int chunksizeGD = 5; //default int.TryParse(AppSetting.settings.GetSettingsAsString(SettingsKey.GD_ChunksSize), out chunksizeGD); item.ChunkUploadSize = chunksizeGD * 1024 * 1024; if (string.IsNullOrEmpty(item.UploadID)) //create upload id { if (string.IsNullOrEmpty(item.To.node.Parent.Info.ID)) { throw new Exception("Can't get root id."); } string parentid = item.To.node.Parent.Info.ID; string mimeType = Get_mimeType.Get_mimeType_From_FileExtension(item.To.node.GetExtension()); string jsondata = "{\"title\": \"" + item.From.node.Info.Name + "\", \"mimeType\": \"" + mimeType + "\", \"parents\": [{\"id\": \"" + parentid + "\"}]}"; item.UploadID = gdclient.Files.Insert_ResumableGetUploadID(jsondata, mimeType, item.From.node.Info.Size); } ItemsTransferWork.Add(new TransferBytes(item, this, gdclient)); return; #endregion case CloudType.Mega: #region Mega MegaApiClient MegaClient = MegaNz.GetClient(rootnodeto.NodeType.Email); item.buffer = new byte[128 * 1024]; if (string.IsNullOrEmpty(item.UploadID)) //create upload id { MegaNz.AutoCreateFolder(item.To.node.Parent); //auto create folder item.UploadID = MegaClient.RequestUrlUpload(item.From.node.Info.Size); //Make Upload url } item.From.stream = MegaApiClient.MakeEncryptStreamForUpload(item.From.stream, item.From.node.Info.Size, item.dataCryptoMega); //make encrypt stream from file ItemsTransferWork.Add(new TransferBytes(item, this, MegaClient)); return; #endregion } }
static void Main(string[] args) { //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents DriveService.Scope.DriveAppdata, // view and manage its own configuration data DriveService.Scope.DriveAppsReadonly, // view your drive apps DriveService.Scope.DriveFile, // view and manage files created by this app DriveService.Scope.DriveMetadataReadonly, // view metadata for files DriveService.Scope.DriveReadonly, // view files and documents on your drive DriveService.Scope.DriveScripts }; // modify your app scripts DriveService service = GDriveAccount.Authenticate("*****@*****.**", "Columbia State-99db1bd2a00e.json", scopes); if (service == null) { Console.WriteLine("Authentication error"); Console.ReadLine(); } DriveDir(service, "0Byi5ne7d961QVS1XOGlPaTRKc28"); try { ChildrenResource.ListRequest request1 = service.Children.List("0Byi5ne7d961QVS1XOGlPaTRKc28"); int j = 1; request1.MaxResults = 1000; List <string> folders = new List <string>(); List <string> files = new List <string>(); do { try { ChildList children = request1.Execute(); foreach (ChildReference child in children.Items) { //Console.WriteLine("{0} File Id: {1}", j, child.Id); File file = service.Files.Get(child.Id).Execute(); if (file.MimeType == "application/vnd.google-apps.folder") { folders.Add(file.Title); } else { files.Add(file.Title); } //Console.WriteLine("Title: {0} - MIME type: {1}", file.Title, file.MimeType); //Console.WriteLine(); //j++; } request1.PageToken = children.NextPageToken; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); request1.PageToken = null; } } while (!String.IsNullOrEmpty(request1.PageToken)); foreach (string dir in folders) { Console.WriteLine(dir); } // Listing files with search. // This searches for a directory with the name DiamtoSample string Q = "title = 'Files' and mimeType = 'application/vnd.google-apps.folder'"; //string Q = "mimeType = 'application/vnd.google-apps.folder'"; IList <File> _Files = GoogleDrive.GetFiles(service, null); foreach (File item in _Files) { Console.WriteLine(item.Title + " " + item.MimeType); } // If there isn't a directory with this name lets create one. if (_Files.Count == 0) { _Files.Add(GoogleDrive.createDirectory(service, "Files1", "Files1", "root")); } // We should have a directory now because we either had it to begin with or we just created one. if (_Files.Count != 0) { // This is the ID of the directory string directoryId = _Files[0].Id; //Upload a file //File newFile = DaimtoGoogleDriveHelper.uploadFile(service, @"c:\GoogleDevelop\dummyUploadFile.txt", directoryId); File newFile = GoogleDrive.uploadFile(service, @"c:\Games\gtasamp.md5", directoryId); // Update The file //File UpdatedFile = DaimtoGoogleDriveHelper.updateFile(service, @"c:\GoogleDevelop\dummyUploadFile.txt", directoryId, newFile.Id); File UpdatedFile = GoogleDrive.updateFile(service, @"c:\Games\gtasamp.md5", directoryId, newFile.Id); // Download the file GoogleDrive.downloadFile(service, newFile, @"C:\Games\download.txt"); // delete The file FilesResource.DeleteRequest request = service.Files.Delete(newFile.Id); request.Execute(); } // Getting a list of ALL a users Files (This could take a while.) _Files = GoogleDrive.GetFiles(service, null); foreach (File item in _Files) { Console.WriteLine(item.Title + " " + item.MimeType); } } catch (Exception ex) { int i = 1; } Console.ReadLine(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); MainActivity.context = Android.App.Application.Context; CrossCurrentActivity.Current.Init(this, savedInstanceState); // Initialize the SDK CloudRail.AppKey = "5aeb7a5d53d06b4cef821f14"; // Inizialize the Google Drive service. GoogleDrive gdrive = new GoogleDrive( this, "870232221465-mbejvcpr04tl0e51885vo37g2hlqgu6k.apps.googleusercontent.com", "", //"com.googleusercontent.apps.870232221465-mbejvcpr04tl0e51885vo37g2hlqgu6k:/oauth2redirect", "com.chkansaku.fehsenproj:/oauth2redirect", "state" ); // Now we enable the use of the advanced authentication, meaning the one that // does not use WebViews. //gdrive.UseAdvancedAuthentication(); // We're logging in the user. This will take them to an on-device browser. After finishing // the login process, the website will send them back to our app. //gdrive.Login(); ICloudStorage service; service = gdrive; Stream result; gdrive.UseAdvancedAuthentication(); void backfunc() { //result = service.Download("/Pictures/FEH/test.png"); //String temp = gdrive.UserLogin; gdrive.Login(); /*var sdCardPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath; * var filePath = System.IO.Path.Combine(sdCardPath, "test"); * var stream = new FileStream(filePath, FileMode.Create); * Bitmap bp = BitmapFactory.DecodeStream(result); * bp.Compress(Bitmap.CompressFormat.Png, 100, stream); * stream.Close(); * bp.Recycle(); * Android.Media.MediaScannerConnection.ScanFile(this, new String[] { sdCardPath + "/" + "test" }, null, null); */ //Toast.MakeText(this, "calling backfunc", ToastLength.Short).Show(); }; //PerformBackgroundOp(gdrive); //ThreadPool.QueueUserWorkItem(o => backfunc()); //Stream result = service.Download("/Pictures/FEH/test.png"); // handle exceptions created when service is cancelled // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get UI stuff from layout Button btnCreate = FindViewById <Button>(Resource.Id.btnCreate); Button btnAdd = FindViewById <Button>(Resource.Id.btnAdd); Button btnDelete = FindViewById <Button>(Resource.Id.btnDelete); Button btnAdjust = FindViewById <Button>(Resource.Id.btnAdjustCropRect); EditText editText = FindViewById <EditText>(Resource.Id.fileName); gridView = FindViewById <GridView>(Resource.Id.gridView); adapter = new ImageAdapter(this); gridView.Adapter = adapter; // listen for gridview item clicks gridView.ItemClick += (sender, e) => { var imageIntent = new Intent(); imageIntent.SetType("image/*"); imageIntent.SetAction(Intent.ActionGetContent); StartActivityForResult( Intent.CreateChooser(imageIntent, "Select photo"), e.Position); }; // create button listeners btnAdd.Click += (sender, e) => // + { adapter.AddNewItem(); }; btnDelete.Click += (sender, e) => // - { adapter.RemoveItem(); }; btnCreate.Click += (sender, e) => // Create collage { if (adapter.GridViewNotEmpty()) { if (_upperBound == 0 && _lowerBound == 0) { // if it's not been adjusted yet, then set // it to default values using the ratio int[] dims = adapter.GetImgDims().ToArray(); _upperBound = 0; _lowerBound = dims[1] * 348 / 2208; } // call the function to create the stacked image adapter.StackMultipleImages(_upperBound, _lowerBound); // launch a new Final Render View Activity var intent = new Intent(); intent.SetClass(MainActivity.GetAppContext(), typeof(FinalRenderViewActivity)); intent.PutExtra("outFileName", editText.Text.ToString()); StartActivity(intent); // reset the values back to initial editText.Text = null; _upperBound = 0; _lowerBound = 0; } else { Toast.MakeText(this, "You must choose at least 1 image!", ToastLength.Short).Show(); } }; btnAdjust.Click += (sender, e) => { // launch a new Adjust Crop Rect Activity if (adapter.GridViewNotEmpty()) { var intent = new Intent(); intent.SetClass(this, typeof(AdjustCropRectActivity)); intent.PutExtra("imgPath", adapter.GetFirstNonEmptyImgPath()); intent.PutExtra("dims", adapter.GetImgDims().ToArray()); intent.PutExtra("upperValue", _upperBound); intent.PutExtra("lowerValue", _lowerBound); StartActivityForResult(intent, ADJUST_CROP_MARGINS_REQUEST); } else { Toast.MakeText(this, "Please load an image", ToastLength.Short).Show(); } }; }
async void PerformBackgroundOp(GoogleDrive gd) { await Task.Run(() => gd.Login()); }
/// <summary> /// Saves a zip of the user's images to GoogleDrive, if configured. /// </summary> /// <exception cref="MyFlightbookException"></exception> /// <param name="activeBrand">The brand to use. Current brand is used if null.</param> /// <param name="gd">The GoogleDrive object to use - Must be initialized and refreshed!</param> /// <returns>True for success</returns> public async Task <IReadOnlyDictionary <string, string> > BackupImagesToGoogleDrive(GoogleDrive gd, Brand activeBrand = null) { if (activeBrand == null) { activeBrand = Branding.CurrentBrand; } if (gd == null) { throw new ArgumentNullException("gd"); } if (User.GoogleDriveAccessToken == null) { throw new MyFlightbookException(Resources.Profile.errNotConfiguredGoogleDrive); } using (MemoryStream ms = ZipOfImagesForUser(activeBrand)) { return(await gd.PutFile(ms, BackupImagesFilename(activeBrand, true), "application/zip")); } }
/// <summary> /// Saves a the user's logbook to GoogleDrive, if configured. /// </summary> /// <exception cref="MyFlightbookException"></exception> /// <exception cref="UnauthorizedAccessException"></exception> /// <param name="gd">The GoogleDrive object to use - Must be initialized and refreshed!</param> /// <param name="activeBrand">The brand to use. Current brand is used if null.</param> /// <returns>True for success</returns> public async Task <IReadOnlyDictionary <string, string> > BackupToGoogleDrive(GoogleDrive gd, Brand activeBrand = null) { if (gd == null) { throw new ArgumentNullException("gd"); } if (User.GoogleDriveAccessToken == null) { throw new MyFlightbookException(Resources.Profile.errNotConfiguredGoogleDrive); } if (activeBrand == null) { activeBrand = Branding.CurrentBrand; } return(await gd.PutFile(BackupFilename(activeBrand), LogbookDataForBackup(), "text/csv")); }
public static void CreateFolderUrl() { var url = "https://www.googleapis.com/drive/v2/files?supportsTeamDrives=true"; Assert.AreEqual(url, GoogleDrive.CreateFolderUrl(true)); }
public static void CreateFolderUrl() { var url = "https://www.googleapis.com/drive/v2/files?supportsTeamDrives=true&teamDriveId=id&includeTeamDriveItems=true&corpora=teamDrive"; Assert.AreEqual(url, GoogleDrive.CreateFolderUrl("id")); }
public async Task <Account> CreateAccountAsync(AccountInfo info) { var token = new CancellationToken(); var storage = new Glacier(info.StorageVault, info.StorageRootPath, info.StorageAccessKeyId, info.StorageSecretAccessKey, info.StorageRegionEndpoint); await storage.InitAsync(token); var account = new Account(storage); var accountCredPath = "accounts/" + info.AccountName + "/drive-credentials/"; foreach (var d in info.Drives) { switch (d.DriveType) { case DriveType.GoogleDrive: var drive = await GoogleDrive.CreateInstance(account, d.DriveId, GoogleClientSecrets.Load(new MemoryStream(Resources.client_secret)).Secrets, d.DriveRootPath, accountCredPath + d.DriveId, token); drive.ImageMaxSize = d.DriveImageMaxSize; await drive.GetServiceAsync(token); account.Drives.Add(drive); break; case DriveType.LocalDrive: var localDrive = new Local.LocalDrive(account, d.DriveId, d.DriveRootPath) { ImageMaxSize = d.DriveImageMaxSize }; account.Drives.Add(localDrive); break; default: throw new NotSupportedException("Drive with this type is not supported"); } } var accountInventoryPath = "accounts/" + info.AccountName + "/glacier-inventory.xml"; using (var store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null)) { if (store.FileExists(accountInventoryPath)) { using (var input = store.OpenFile(accountInventoryPath, FileMode.Open)) { var reader = new StreamReader(input); var xml = await reader.ReadToEndAsync(); var doc = XDocument.Load(new XmlTextReader(new StringReader(xml))); var glacierDrive = new GlacierPseudoDrive(account, "inventory", doc); account.Drives.Add(glacierDrive); } } } return(account); }
private void UploadLogic() { try { do { UploadTokenSource?.Token.ThrowIfCancellationRequested(); ThreadControlName = "Pause"; this.mUpObj = null; try { this.mUpObj = FileList.First(x => !x.IsOver); } catch (Exception ex) { ex.Message.InfoLognConsole(); } if (!(this.mUpObj is null)) { this.mUpObj.RefreshData(); string remot = this.mUpObj.RemotePath; MainName = "[Uploading]" + this.mUpObj.FileName; NowProcressingContent = this.mUpObj; ProcessNow.SetValue(0, 0, "Initialize upload (MD5 File Checking...)"); ProcessNowState = true; bool isSuccess = false; bool isFirstTime = (this.mDatabase is null) ? !System.IO.File.Exists(GoogleDrive.GetUploadStatusPath(this.mUpObj)) : mDatabase.GetFileUploadID(this.mUpObj.ID).IsNullOrEmptyOrWhiltSpace(); if (isFirstTime) { //if this is the first time this file is being upload. var tID = Service.RemoteFileExists(this.mUpObj, remot, false); if (tID.IsNullOrEmptyOrWhiltSpace()) { ProcessNowState = false; if (this.mUpObj.IsChangeFather) { Google.Apis.Drive.v3.Data.File parent; string nowParentName = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(this.mUpObj.FullPath)); string remotePath = this.mUpObj.RemotePath.Replace(nowParentName, this.mUpObj.OldFatherPath); if (!remotePath.IsNullOrEmptyOrWhiltSpace()) { parent = Service.GetGoogleFolderByPath(remotePath); Service.UpdateFile(parent.Id, nowParentName); } } isSuccess = this.mUpObj.Upload(Service); } else { ProcessNowState = false; isSuccess = true; mDatabase.SetUploadStatus(this.mUpObj.ID, tID, true); } } else { //if this is a resume upload. ProcessNowState = false; isSuccess = this.mUpObj.Upload(Service); } if (UploadTokenSource?.Token.IsCancellationRequested ?? false) { break; } Processed += this.mUpObj.Length; this.mUpObj.IsOver = isSuccess; } else { ProcessNow.SetValue(0, 0, "Done."); break; } } while (true); }
public override void Execute(Message msg, VkApi client) { try { if (DataBase.Students.Exist(Students.ExistOption.VKId, msg.UserId.ToString())) { string str = msg.Body; String[] words = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (words.Length != 1) { throw new FormatException("Неверный ввод"); } if (DataBase.Tasks.CanSaveSolution(DB.Tasks.Tasks.IdType.VKId, msg.UserId.ToString())) { int cnt = 0; var student = DataBase.Students.GetByID(Students.IdType.VKId, msg.UserId.ToString()); foreach (var attachment in msg.Attachments) { if (attachment.Type == typeof(Photo)) { Photo photo = attachment.Instance as Photo; if (downloadFile(getUrlOfBigPhoto(photo))) { GoogleDrive.Upload(student, TMP_FILE_PATH, student.CurrentTask + "_" + cnt); System.IO.File.Delete(TMP_FILE_PATH); cnt++; } } } if (msg.Attachments.Count == 0) { throw new ArgumentException("Вы ничего не прикрепили"); } else if (cnt == msg.Attachments.Count) { send(client, msg, AnswerOk); } else { send(client, msg, $"Я смог загрузить {cnt}/{msg.Attachments.Count} вложений"); } } else { send(client, msg, AnswerBadAnswer); } } else { send(client, msg, "Данный аккаунт незарегистрирован, используйте /register"); } Logger.Log(Logger.Module.VK, Logger.Type.Info, $"{msg.UserId}: {msg.Body}"); } catch (ArgumentException exception) { send(client, msg, exception.Message); Logger.Log(Logger.Module.VK, Logger.Type.Warning, $"{msg.UserId}: {msg.Body} ({exception.Message})"); } catch (Exception exception) { send(client, msg, AnswerError + "(" + exception.Message + ")\n" + AnswerInfo); Logger.Log(Logger.Module.VK, Logger.Type.Warning, $"{msg.UserId}: {msg.Body} ({exception.Message})"); } }
private async Task <bool> BackupToCloud() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Text.StringBuilder sbFailures = new System.Text.StringBuilder(); List <EarnedGrauity> lstUsersWithCloudBackup = EarnedGrauity.GratuitiesForUser(string.Empty, Gratuity.GratuityTypes.CloudBackup); if (!String.IsNullOrEmpty(UserRestriction)) { lstUsersWithCloudBackup.RemoveAll(eg => eg.Username.CompareCurrentCultureIgnoreCase(UserRestriction) != 0); } foreach (EarnedGrauity eg in lstUsersWithCloudBackup) { StorageID sid = StorageID.None; if (eg.UserProfile != null && ((sid = eg.UserProfile.BestCloudStorage) != StorageID.None) && eg.CurrentStatus != EarnedGrauity.EarnedGratuityStatus.Expired) { Profile pf = eg.UserProfile; LogbookBackup lb = new LogbookBackup(pf); switch (sid) { case StorageID.Dropbox: { MFBDropbox.TokenStatus ts = new MFBDropbox().ValidateDropboxToken(pf, true, true); if (ts == MFBDropbox.TokenStatus.None) { continue; } try { Dropbox.Api.Files.FileMetadata result = null; result = await lb.BackupToDropbox(Branding.CurrentBrand); sb.AppendFormat(CultureInfo.CurrentCulture, "Dropbox: user {0} ", pf.UserName); if (ts == MFBDropbox.TokenStatus.oAuth1) { sb.Append("Token UPDATED from oauth1! "); } sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName); System.Threading.Thread.Sleep(0); result = await lb.BackupImagesToDropbox(Branding.CurrentBrand); System.Threading.Thread.Sleep(0); sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName); } catch (Dropbox.Api.ApiException <Dropbox.Api.Files.UploadError> ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Dropbox.Api.ApiException<Dropbox.Api.Files.UploadError) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); string szMessage = (ex.ErrorResponse.IsPath && ex.ErrorResponse.AsPath != null && ex.ErrorResponse.AsPath.Value.Reason.IsInsufficientSpace) ? Resources.LocalizedText.DropboxErrorOutOfSpace : ex.Message; util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, szMessage, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (Dropbox.Api.AuthException ex) { // De-register dropbox. pf.DropboxAccessToken = string.Empty; pf.FCommit(); sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (AuthException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (Dropbox.Api.BadInputException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (BadInputException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), false, false); } catch (Dropbox.Api.HttpException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (HttpException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (Dropbox.Api.AccessException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (AccessException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (Dropbox.Api.DropboxException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Base dropbox exception) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (UnauthorizedAccessException ex) { // De-register dropbox. pf.DropboxAccessToken = string.Empty; pf.FCommit(); sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (MyFlightbookException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.DropboxFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.DropboxFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (System.IO.FileNotFoundException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message); } catch (Exception ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Dropbox FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n{3}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message, ex.StackTrace); if (ex.InnerException != null) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "Inner exception: {0}\r\n{1}", ex.InnerException.Message, ex.InnerException.StackTrace); } } } break; case StorageID.OneDrive: { try { if (pf.OneDriveAccessToken == null) { throw new UnauthorizedAccessException(); } Microsoft.OneDrive.Sdk.Item item = null; OneDrive od = new OneDrive(pf.OneDriveAccessToken); item = await lb.BackupToOneDrive(od); sb.AppendFormat(CultureInfo.CurrentCulture, "OneDrive: user {0} ", pf.UserName); sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName); System.Threading.Thread.Sleep(0); item = await lb.BackupImagesToOneDrive(od, Branding.CurrentBrand); System.Threading.Thread.Sleep(0); sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName); // if we are here we were successful, so save the updated refresh token if (String.Compare(pf.OneDriveAccessToken.RefreshToken, od.AuthState.RefreshToken, StringComparison.Ordinal) != 0) { pf.OneDriveAccessToken.RefreshToken = od.AuthState.RefreshToken; pf.FCommit(); } } catch (Microsoft.OneDrive.Sdk.OneDriveException ex) { string szMessage = OneDrive.MessageForException(ex); sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (OneDriveException) {0}: {1}\r\n\r\n", pf.UserName, szMessage + " " + ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, szMessage, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (MyFlightbookException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (UnauthorizedAccessException ex) { // De-register oneDrive. pf.OneDriveAccessToken = null; pf.FCommit(); sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.OneDriveFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.OneDriveFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (System.IO.FileNotFoundException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message); } catch (Exception ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n{3}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message, ex.StackTrace); } } break; case StorageID.GoogleDrive: { try { if (pf.GoogleDriveAccessToken == null) { throw new UnauthorizedAccessException(); } GoogleDrive gd = new GoogleDrive(pf.GoogleDriveAccessToken); bool fRefreshed = await gd.RefreshAccessToken(); sb.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive: user {0} ", pf.UserName); IReadOnlyDictionary <string, string> meta = await lb.BackupToGoogleDrive(gd, Branding.CurrentBrand); if (meta != null) { sb.AppendFormat(CultureInfo.CurrentCulture, "Logbook backed up for user {0}...", pf.UserName); } System.Threading.Thread.Sleep(0); meta = await lb.BackupImagesToGoogleDrive(gd, Branding.CurrentBrand); System.Threading.Thread.Sleep(0); if (meta != null) { sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName); } // if we are here we were successful, so save the updated refresh token if (fRefreshed) { pf.FCommit(); } } catch (MyFlightbookException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (MyFlightbookException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.GoogleDriveFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.GoogleDriveFailure, pf.UserFullName, ex.Message, string.Empty), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (UnauthorizedAccessException ex) { // De-register GoogleDrive. pf.GoogleDriveAccessToken = null; pf.FCommit(); sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (UnauthorizedAccess) {0}: {1}\r\n\r\n", pf.UserName, ex.Message); util.NotifyUser(Branding.ReBrand(Resources.EmailTemplates.GoogleDriveFailureSubject, ActiveBrand), Branding.ReBrand(String.Format(CultureInfo.CurrentCulture, Resources.EmailTemplates.GoogleDriveFailure, pf.UserFullName, ex.Message, Resources.LocalizedText.DropboxErrorDeAuthorized), ActiveBrand), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), true, false); } catch (System.IO.FileNotFoundException ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user: FileNotFoundException, no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message); } catch (Exception ex) { sbFailures.AppendFormat(CultureInfo.CurrentCulture, "GoogleDrive FAILED for user (Unknown Exception), no notification sent {0}: {1} {2}\r\n\r\n", pf.UserName, ex.GetType().ToString(), ex.Message); } } break; case StorageID.iCloud: break; default: break; } } } ; util.NotifyAdminEvent("Dropbox report", sbFailures.ToString() + sb.ToString(), ProfileRoles.maskCanReport); return(true); }
public void updateListCourses(DriveService service) { string folderId = "1HiuLTcwX2hdyWeN4zeUZ6kLOf17mFRR1"; List <Google.Apis.Drive.v3.Data.File> filesList = new List <Google.Apis.Drive.v3.Data.File>(); filesList = GoogleDrive.ListFiles(service, folderId); string[] words; string datetimeStr = ""; //foreach (var file in filesList) //{ // ds.Rows.Add(false, file.Name, datetimeStr, file.Name, file.Size.ToString(), "", "", file.Id, file.Size);// i.ToString()); //} foreach (var file in filesList) { if (file.Name.ToLower().IndexOf(".zip") < 0) { continue; } string fileName = file.Name.Replace(".zip", ""); words = fileName.Split('_'); if (words.Length > 2) { words[1] = words[1].Insert(2, ":"); words[2] = words[2].Insert(2, "/"); words[2] = words[2].Insert(5, "/"); datetimeStr = words[1] + ", " + words[2]; if (allCourses.Checked == true) { double sizeMB = ConvertBytesToMegabytes(long.Parse(file.Size.ToString())); string sizeMBString = String.Format("{0:0.00}", sizeMB); ds.Rows.Add(false, words[0], datetimeStr, file.Name, sizeMBString, "", "", file.Id, file.Size);// i.ToString()); } if (coursesNewest.Checked == true) { try { string dateTime3 = datetimeStr; string[] iDateNow = dateTime3.Split(','); DateTime comparingDate = DateTime.ParseExact(iDateNow[1].Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture); DateTime comparingDate_time = Convert.ToDateTime(iDateNow[0]); bool justRemove = true; for (int i = ds.Rows.Count - 1; i >= 0; i--) { string courseName = ds.Rows[i][1].ToString(); if (words[0] == courseName) { string dateTime2 = ds.Rows[i][2].ToString(); string[] iDate = dateTime2.Split(','); DateTime previousDate = DateTime.ParseExact(iDate[1].Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture); DateTime previousDate_time = Convert.ToDateTime(iDate[0]); int result = DateTime.Compare(previousDate, comparingDate); int result_time = DateTime.Compare(previousDate_time, comparingDate_time); if (result < 0) { ds.Rows.RemoveAt(i); } else if (result == 0) { if (result_time <= 0) { ds.Rows.RemoveAt(i); } else { justRemove = false; } } else { justRemove = false; break; } } } if (justRemove == true) { double sizeMB = ConvertBytesToMegabytes(long.Parse(file.Size.ToString())); string sizeMBString = String.Format("{0:0.00}", sizeMB); ds.Rows.Add(false, words[0], datetimeStr, file.Name, sizeMBString, "", "", file.Id, file.Size); } } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); } } } } }
IEnumerator StartAuthentication_internal(boolFuncResult callback ,int trialNumber){ _initInProgress = true; _drive = new GoogleDrive(); _drive.ClientID = "251952116687-o29juik9i0qbl6ktpa0n97cavk8cvip4.apps.googleusercontent.com"; _drive.ClientSecret = "0ZptNq9TwzL7enTtlRUOoZ3_"; var authorization = _drive.Authorize(); yield return StartCoroutine(authorization); if (authorization.Current is Exception) { #if UNITY_EDITOR #endif Exception temp =(authorization.Current as Exception); string res = temp.ToString(); if(res == "GoogleDrive+Exception: Invalid credential."){ callback (true, 1); }else{ callback (false,0); } }else { #if UNITY_EDITOR Debug.Log("User Account: " + _drive.UserAccount); #endif callback (true,0); } _initInProgress = false; }
public SaveAndRetrive() { dal = new DalImplementation(); googleDrive = new GoogleDrive(); }
public static void AboutInfoUrl() { var url = "https://www.googleapis.com/drive/v2/about"; Assert.AreEqual(url, GoogleDrive.AboutInfoUrl()); }
IEnumerator DonwloadAllFilesInFolder_internal(string loadFolderName, string saveFolderPath) { _isFileDownloadProcessing = true; _isFileDownloadDone = false; _isSingleFileDownloadDone = false; string targetId = ""; if (loadFolderName != "") { if (_filesDictionary != null && _filesDictionary.ContainsKey(loadFolderName)) { targetId = _filesDictionary [loadFolderName].ID; } } var listFiles = _drive.ListFolders(recentFolderID); yield return(StartCoroutine(listFiles)); var files = GoogleDrive.GetResult <List <GoogleDrive.File> >(listFiles); if (files != null) { //Processing Number Initialize !! if (!Directory.Exists(saveFolderPath)) { Directory.CreateDirectory(saveFolderPath); } //Processed file count _NumberOfTotalDownloadFile = 0; foreach (var file in files) { if (file.Title.EndsWith(".jpg") || file.Title.EndsWith(".png") || file.Title.EndsWith(".JPG") || file.Title.EndsWith(".PNG")) { _NumberOfTotalDownloadFile += 1; } } _NumberOfProcessedFile = 0; _isSingleFileDownloadDone = true; //Download Start; //fileName Duplicator Check List <string> fileNameList = new List <string>(); foreach (var file in files) { #if UNITY_EDITOR Debug.Log(file); #endif if (_isFileDownloadCancel) { break; } if (file.Title.EndsWith(".jpg") || file.Title.EndsWith(".png") || file.Title.EndsWith(".JPG") || file.Title.EndsWith(".PNG")) { var download = _drive.DownloadFile(file); yield return(StartCoroutine(download)); var data = GoogleDrive.GetResult <byte[]>(download); //Name Duplicator checker string finalFileTitle = file.Title; bool bIsDuplicatedFileName = false; int duplicatedNumber = 0; foreach (string title in fileNameList) { if (title == file.Title) { bIsDuplicatedFileName = true; duplicatedNumber++; } } if (bIsDuplicatedFileName) { finalFileTitle += duplicatedNumber.ToString(); } try{ FileStream fs = new FileStream(saveFolderPath + "/" + finalFileTitle, FileMode.Create); fs.Write(data, 0, data.Length); fs.Dispose(); fileNameList.Add(file.Title); //----- ++_NumberOfProcessedFile; _isSingleFileDownloadDone = true; }catch { _isFileDownloadCancel = true; } } } } else { #if UNITY_EDITOR Debug.Log(listFiles.Current); #endif } _isFileDownloadDone = true; }
public UploadResult UploadFile(Stream stream, string fileName) { FileUploader fileUploader = null; FileDestination fileDestination; switch (Info.DataType) { case EDataType.Image: fileDestination = Info.TaskSettings.ImageFileDestination; break; case EDataType.Text: fileDestination = Info.TaskSettings.TextFileDestination; break; default: case EDataType.File: fileDestination = Info.TaskSettings.FileDestination; break; } switch (fileDestination) { case FileDestination.Dropbox: NameParser parser = new NameParser(NameParserType.URL); string uploadPath = parser.Parse(Dropbox.TidyUploadPath(Program.UploadersConfig.DropboxUploadPath)); fileUploader = new Dropbox(Program.UploadersConfig.DropboxOAuthInfo, Program.UploadersConfig.DropboxAccountInfo) { UploadPath = uploadPath, AutoCreateShareableLink = Program.UploadersConfig.DropboxAutoCreateShareableLink, ShareURLType = Program.UploadersConfig.DropboxURLType }; break; case FileDestination.GoogleDrive: fileUploader = new GoogleDrive(Program.UploadersConfig.GoogleDriveOAuth2Info) { IsPublic = Program.UploadersConfig.GoogleDriveIsPublic }; break; case FileDestination.RapidShare: fileUploader = new RapidShare(Program.UploadersConfig.RapidShareUsername, Program.UploadersConfig.RapidSharePassword, Program.UploadersConfig.RapidShareFolderID); break; case FileDestination.SendSpace: fileUploader = new SendSpace(APIKeys.SendSpaceKey); switch (Program.UploadersConfig.SendSpaceAccountType) { case AccountType.Anonymous: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey); break; case AccountType.User: SendSpaceManager.PrepareUploadInfo(APIKeys.SendSpaceKey, Program.UploadersConfig.SendSpaceUsername, Program.UploadersConfig.SendSpacePassword); break; } break; case FileDestination.Minus: fileUploader = new Minus(Program.UploadersConfig.MinusConfig, Program.UploadersConfig.MinusOAuth2Info); break; case FileDestination.Box: fileUploader = new Box(Program.UploadersConfig.BoxOAuth2Info) { FolderID = Program.UploadersConfig.BoxSelectedFolder.id, Share = Program.UploadersConfig.BoxShare }; break; case FileDestination.Ge_tt: if (Program.UploadersConfig.IsActive(FileDestination.Ge_tt)) { fileUploader = new Ge_tt(APIKeys.Ge_ttKey) { AccessToken = Program.UploadersConfig.Ge_ttLogin.AccessToken }; } break; case FileDestination.Localhostr: fileUploader = new Hostr(Program.UploadersConfig.LocalhostrEmail, Program.UploadersConfig.LocalhostrPassword) { DirectURL = Program.UploadersConfig.LocalhostrDirectURL }; break; case FileDestination.CustomFileUploader: if (Program.UploadersConfig.CustomUploadersList.IsValidIndex(Program.UploadersConfig.CustomFileUploaderSelected)) { fileUploader = new CustomFileUploader(Program.UploadersConfig.CustomUploadersList[Program.UploadersConfig.CustomFileUploaderSelected]); } break; case FileDestination.FTP: int index = Info.TaskSettings.OverrideFTP ? Info.TaskSettings.FTPIndex.BetweenOrDefault(0, Program.UploadersConfig.FTPAccountList.Count - 1) : Program.UploadersConfig.GetFTPIndex(Info.DataType); FTPAccount account = Program.UploadersConfig.FTPAccountList.ReturnIfValidIndex(index); if (account != null) { if (account.Protocol == FTPProtocol.SFTP) { fileUploader = new SFTP(account); } else { fileUploader = new FTPUploader(account); } } break; case FileDestination.SharedFolder: int idLocalhost = Program.UploadersConfig.GetLocalhostIndex(Info.DataType); if (Program.UploadersConfig.LocalhostAccountList.IsValidIndex(idLocalhost)) { fileUploader = new SharedFolderUploader(Program.UploadersConfig.LocalhostAccountList[idLocalhost]); } break; case FileDestination.Email: using (EmailForm emailForm = new EmailForm(Program.UploadersConfig.EmailRememberLastTo ? Program.UploadersConfig.EmailLastTo : string.Empty, Program.UploadersConfig.EmailDefaultSubject, Program.UploadersConfig.EmailDefaultBody)) { emailForm.Icon = ShareXResources.Icon; if (emailForm.ShowDialog() == DialogResult.OK) { if (Program.UploadersConfig.EmailRememberLastTo) { Program.UploadersConfig.EmailLastTo = emailForm.ToEmail; } fileUploader = new Email { SmtpServer = Program.UploadersConfig.EmailSmtpServer, SmtpPort = Program.UploadersConfig.EmailSmtpPort, FromEmail = Program.UploadersConfig.EmailFrom, Password = Program.UploadersConfig.EmailPassword, ToEmail = emailForm.ToEmail, Subject = emailForm.Subject, Body = emailForm.Body }; } else { IsStopped = true; } } break; case FileDestination.Jira: fileUploader = new Jira(Program.UploadersConfig.JiraHost, Program.UploadersConfig.JiraOAuthInfo, Program.UploadersConfig.JiraIssuePrefix); break; case FileDestination.Mega: fileUploader = new Mega(Program.UploadersConfig.MegaAuthInfos, Program.UploadersConfig.MegaParentNodeId); break; case FileDestination.AmazonS3: fileUploader = new AmazonS3(Program.UploadersConfig.AmazonS3Settings); break; case FileDestination.Pushbullet: fileUploader = new Pushbullet(Program.UploadersConfig.PushbulletSettings); break; } if (fileUploader != null) { PrepareUploader(fileUploader); return(fileUploader.Upload(stream, fileName)); } return(null); }
public byte[] DownloadFile(string fileId) { var drive = new GoogleDrive(); return drive.DownloadFile(fileId); }