Пример #1
0
    protected async void lnkSaveOneDrive_Click(object sender, EventArgs e)
    {
        MyFlightbook.Profile pf = MyFlightbook.Profile.GetUser(Page.User.Identity.Name);
        LogbookBackup        lb = new LogbookBackup(pf);

        if (pf.OneDriveAccessToken == null || String.IsNullOrEmpty(pf.OneDriveAccessToken.RefreshToken))
        {
            return;
        }
        try
        {
            OneDrive od = new OneDrive(pf.OneDriveAccessToken);
            await lb.BackupToOneDrive(od).ConfigureAwait(false);

            if (ckIncludeImages.Checked)
            {
                await lb.BackupImagesToOneDrive(od).ConfigureAwait(false);
            }

            // if we are here we were successful, so save the updated refresh token
            pf.OneDriveAccessToken = od.AuthState;
            pf.FCommit();

            lblDropBoxSuccess.Visible = true;
        }
        catch (Exception ex) when(ex is OneDriveMFBException || ex is MyFlightbookException || !(ex is OutOfMemoryException))
        {
            ShowDropboxError(ex.Message);
        }
    }
Пример #2
0
        /// <summary>
        /// Saves a zip of the user's images to OneDrive, if configured.
        /// </summary>
        /// <exception cref="MyFlightbookException"></exception>
        /// <exception cref="OneDriveMFBException"></exception>
        /// <param name="activeBrand">The brand to use.  Current brand is used if null.</param>
        /// <param name="od">The OneDrive object to use (one will be initialized, if necessary)</param>
        public async Task <bool> BackupImagesToOneDrive(OneDrive od = null, Brand activeBrand = null)
        {
            if (activeBrand == null)
            {
                activeBrand = Branding.CurrentBrand;
            }

            if (User.OneDriveAccessToken == null)
            {
                throw new MyFlightbookException(Resources.Profile.errNotConfiguredOneDrive);
            }

            if (od == null)
            {
                od = new OneDrive(User);
            }

            using (FileStream fs = new FileStream(Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite, FileShare.None, Int16.MaxValue, FileOptions.DeleteOnClose))
            {
                WriteZipOfImagesToStream(fs, activeBrand);
                bool result = await od.PutFileDirect(BackupImagesFilename(activeBrand), fs, "application/zip").ConfigureAwait(true);

                return(result);
            }
        }
Пример #3
0
        public void OneDriveListFolders(OneDriveFileInfo fileEntry, TreeNode tnParent)
        {
            Application.DoEvents();
            OneDrive         oneDrive         = new OneDrive(Config.OneDriveV2OAuth2Info);
            OneDriveFileList oneDrivePathInfo = oneDrive.GetPathInfo(fileEntry.id);

            tnParent.Nodes.Clear();
            foreach (OneDriveFileInfo folder in oneDrivePathInfo.value)
            {
                OneDriveAddFolder(folder, tnParent);
            }
        }
Пример #4
0
        private async Task <bool> BackupOneDrive(LogbookBackup lb, Profile pf, StringBuilder sb, StringBuilder sbFailures)
        {
            try
            {
                if (pf.OneDriveAccessToken == null)
                {
                    throw new UnauthorizedAccessException();
                }

                OneDrive od = new OneDrive(pf.OneDriveAccessToken);
                if (await lb.BackupToOneDrive(od).ConfigureAwait(false))
                {
                    sb.AppendFormat(CultureInfo.CurrentCulture, "OneDrive: user {0} Logbook backed up for user {0}...", pf.UserName);
                }

                System.Threading.Thread.Sleep(0);
                if (await lb.BackupImagesToOneDrive(od, Branding.CurrentBrand).ConfigureAwait(false))
                {
                    sb.AppendFormat(CultureInfo.CurrentCulture, "and images backed up for user {0}.\r\n \r\n", pf.UserName);
                }

                System.Threading.Thread.Sleep(0);
                // if we are here we were successful, so save the updated refresh token
                pf.OneDriveAccessToken = od.AuthState;
                pf.FCommit();
            }
            catch (Exception ex) when(ex is OneDriveMFBException || ex is MyFlightbookException)
            {
                sbFailures.AppendFormat(CultureInfo.CurrentCulture, "OneDrive FAILED for user (OneDriveException) {0}: {1}\r\n\r\n", pf.UserName, ex.Message + " " + 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) when(!(ex is OutOfMemoryException))
            {
                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);
            }
            return(true);
        }
Пример #5
0
        protected override async void OnStart()
        {
            LocalStoragePath = await DependencyService.Get <LocalStorage>().GetLocalStoragePath();

            // Handle when your app starts
            Library      = new Library();
            UserSettings = await Library.GetSettings();

            Player   = new Player();
            OneDrive = new OneDrive();
            await OneDrive.GetToken();

            Player.PlayerState = Player.StateStopped;
            Player.GetNowPlaying();
        }
 void onEditWin(object s, RoutedEventArgs e)
 {
     if (pcLogicDataGridRO.SelectedItems.Count > 0 &&
         pcLogicDataGridRO.SelectedItems[0] is PcLogic)
     {
         var localdb = OneDrive.Folder($@"{DbLogHelper._dbSubP}LocalDb({(pcLogicDataGridRO.SelectedItems[0] as PcLogic).MachineName}).mdf");
         if (File.Exists(localdb))
         {
             new RODBView(localdb).ShowDialog();
         }
     }
     else
     {
         MessageBox.Show($"{pcLogicDataGridRO.SelectedItems[0]}", "Not there");
     }
 }
Пример #7
0
        /// <summary>
        /// Restore the watch items from OneDrive
        /// </summary>
        /// <returns></returns>
        public async Task <bool> Restore()
        {
            try
            {
                string CompressedFile = "pebble_time_manager_backup.zip";

                //Get backup file
                await OneDrive.DownloadAsync("Backup", CompressedFile);

                Windows.Storage.StorageFolder LocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Stream FileStream = await LocalFolder.OpenStreamForReadAsync(CompressedFile);

                using (ZipArchive zipArchive = new ZipArchive(FileStream, ZipArchiveMode.Read))
                {
                    foreach (ZipArchiveEntry entry in zipArchive.Entries)
                    {
                        using (Stream entryStream = entry.Open())
                        {
                            byte[] buffer = new byte[entry.Length];
                            entryStream.Read(buffer, 0, buffer.Length);
                            // Create a file to store the contents
                            StorageFile uncompressedFile = await LocalFolder.CreateFileAsync(entry.Name, CreationCollisionOption.ReplaceExisting);

                            // Store the contents
                            using (IRandomAccessStream uncompressedFileStream =
                                       await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                using (Stream outstream = uncompressedFileStream.AsStreamForWrite())
                                {
                                    outstream.Write(buffer, 0, buffer.Length);
                                    outstream.Flush();
                                }
                            }

                            System.Diagnostics.Debug.WriteLine("Restore exception: " + entry.Name);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine("Restore exception: " + exp.Message);
                return(false);
            }

            return(true);
        }
Пример #8
0
        /// <summary>
        /// Saves a the user's logbook to OneDrive, if configured.
        /// </summary>
        /// <exception cref="MyFlightbookException"></exception>
        /// <exception cref="OneDriveMFBException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <param name="od">The OneDrive object to use (one will be initialized, if necessary)</param>
        /// <param name="activeBrand">The brand to use.  Current brand is used if null.</param>
        public async Task <bool> BackupToOneDrive(OneDrive od = null, Brand activeBrand = null)
        {
            if (User.OneDriveAccessToken == null)
            {
                throw new MyFlightbookException(Resources.Profile.errNotConfiguredOneDrive);
            }

            if (activeBrand == null)
            {
                activeBrand = Branding.CurrentBrand;
            }

            if (od == null)
            {
                od = new OneDrive(User.OneDriveAccessToken);
            }

            return(await od.PutFileDirect(BackupFilename(activeBrand), LogbookDataForBackup(), "text/csv").ConfigureAwait(true));
        }
Пример #9
0
        /// <summary>
        /// Saves a the user's logbook to OneDrive, if configured.
        /// </summary>
        /// <exception cref="MyFlightbookException"></exception>
        /// <exception cref="Microsoft.OneDrive.Sdk.OneDriveException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <param name="od">The OneDrive object to use (one will be initialized, if necessary)</param>
        /// <param name="activeBrand">The brand to use.  Current brand is used if null.</param>
        public async Task <Microsoft.OneDrive.Sdk.Item> BackupToOneDrive(OneDrive od = null, Brand activeBrand = null)
        {
            if (User.OneDriveAccessToken == null)
            {
                throw new MyFlightbookException(Resources.Profile.errNotConfiguredOneDrive);
            }

            if (activeBrand == null)
            {
                activeBrand = Branding.CurrentBrand;
            }

            if (od == null)
            {
                od = new OneDrive(User.OneDriveAccessToken);
            }

            return(await od.PutFile(BackupFilename(activeBrand), LogbookDataForBackup()));
        }
Пример #10
0
        public void SelectStorage(DocumentStorage storage)
        {
            CloudRail.AppKey = "5ad616fe53d06b4cef4eb35c";


            switch (storage)
            {
            case DocumentStorage.Dropbox:
                Dropbox dropbox = new Dropbox(
                    new LocalReceiver(port),
                    "yr0vm4fdyc5m5wq",
                    "ec81w1sde5psdyn",
                    "http://localhost:" + port + "/",
                    "someState"
                    );
                service = dropbox;
                break;

            case DocumentStorage.GoogleDrive:
                GoogleDrive googledrive = new GoogleDrive(
                    new LocalReceiver(port),
                    "452884182377-af4j4heo22mgo04vvg95ol547tih4md7.apps.googleusercontent.com",
                    "1TKbAAkPHtf4DLRdH3os0hL8",
                    "http://localhost:" + port + "/",
                    "someState"
                    );
                service = googledrive;
                break;

            case DocumentStorage.OneDrive:
                OneDrive onedrive = new OneDrive(
                    new LocalReceiver(port),
                    "488bea49-a172-45df-bb6f-a9efb228a4e6",
                    "jD57;nfrylvEJAIWP807[;#",
                    "http://localhost:" + port + "/",
                    "someState"
                    );
                service = onedrive;
                break;
            }
        }
Пример #11
0
        public JsonResult OneDrive(int Id, OneDrive oneDrive)
        {
            // Поиск задания
            if (coreDB.SyncBackup_Tasks.Where(i => i.Id == Id).Include(i => i.OneDrive).FirstOrDefault() is Task item)
            {
                #region Проверка данных
                if (string.IsNullOrWhiteSpace(item.OneDrive.ApplicationId) && string.IsNullOrWhiteSpace(oneDrive.ApplicationId) || (HttpContext.Request.Query.TryGetValue("applicationid", out _) && string.IsNullOrWhiteSpace(oneDrive.ApplicationId)))
                {
                    return(Json(new Text("Настройки 'OneDrive' имеют недопустимое значение, укажите ApplicationId")));
                }

                if (string.IsNullOrWhiteSpace(item.OneDrive.RefreshToken) && string.IsNullOrWhiteSpace(oneDrive.RefreshToken) || (HttpContext.Request.Query.TryGetValue("refreshtoken", out _) && string.IsNullOrWhiteSpace(oneDrive.RefreshToken)))
                {
                    return(Json(new Text("Настройки 'OneDrive' имеют недопустимое значение, укажите RefreshToken")));
                }
                #endregion

                return(Edit(item.OneDrive, oneDrive));
            }

            return(Json(new Text("Задание не найдено")));
        }
        async void onLoaded(object s, RoutedEventArgs e)
        {
            vizroot.IsEnabled = false;
            try
            {
                tbInfo.Text   = $"Loading ...  ";
                tbCurVer.Text = $"{VerHelper.CurVerStr(".NET 5.0")}";

                var itemsSrc = await DbLogHelper.AllPCsAsync();

                tbInfo.Text = $"Loading {itemsSrc.Count} PCs...  ";

                var _localdb = OneDrive.Folder($@"{DbLogHelper._dbSubP}LocalDb({Environment.MachineName}).mdf");
                FileAttributeHelper.RmvAttribute(_localdb, FileAttributes.ReadOnly);
                var _db = A0DbModel.GetLclFl(_localdb);
                await _db.PcLogics.LoadAsync();

                await _db.EvOfInts.LoadAsync();

                //foreach (PcLogic item in ((List<PcLogic>)pcLogicDataGridRO.ItemsSource).Where(r => !r.MachineName.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase)))                    _db.PcLogics.Local.Add(item);

                ((CollectionViewSource)(FindResource("pcLogicViewSource"))).Source = _db.PcLogics.Local;
                ((CollectionViewSource)(FindResource("evOfIntViewSource"))).Source = _db.EvOfInts.Local;

                tbInfo.Text = $"{_db.PcLogics.Local.Count} PCs with {_db.EvOfInts.Local.Count} events.";

                pcLogicDataGridRO.ItemsSource = itemsSrc;
                foreach (var item in itemsSrc)
                {
                    if (item.MachineName.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase))
                    {
                        pcLogicDataGridRO.SelectedItem = item;
                    }
                }
                pcLogicDataGridRO.Focus();
            }
            catch (Exception ex) { ex.Pop();; }
            finally { vizroot.IsEnabled = true; }
        }
Пример #13
0
        /// <summary>
        /// Saves a zip of the user's images to OneDrive, if configured.
        /// </summary>
        /// <exception cref="MyFlightbookException"></exception>
        /// <exception cref="Microsoft.OneDrive.Sdk.OneDriveException"></exception>
        /// <param name="activeBrand">The brand to use.  Current brand is used if null.</param>
        /// <param name="od">The OneDrive object to use (one will be initialized, if necessary)</param>
        public async Task <Microsoft.OneDrive.Sdk.Item> BackupImagesToOneDrive(OneDrive od = null, Brand activeBrand = null)
        {
            if (activeBrand == null)
            {
                activeBrand = Branding.CurrentBrand;
            }

            if (User.OneDriveAccessToken == null)
            {
                throw new MyFlightbookException(Resources.Profile.errNotConfiguredOneDrive);
            }

            if (od == null)
            {
                od = new OneDrive(User.OneDriveAccessToken);
            }

            using (MemoryStream ms = ZipOfImagesForUser(activeBrand))
            {
                return(await od.PutFile(ms, BackupImagesFilename(activeBrand)));
            }
        }
Пример #14
0
        /// <summary>
        /// Saves a zip of the user's images to OneDrive, if configured.
        /// </summary>
        /// <exception cref="MyFlightbookException"></exception>
        /// <exception cref="OneDriveMFBException"></exception>
        /// <param name="activeBrand">The brand to use.  Current brand is used if null.</param>
        /// <param name="od">The OneDrive object to use (one will be initialized, if necessary)</param>
        public async Task <bool> BackupImagesToOneDrive(OneDrive od = null, Brand activeBrand = null)
        {
            if (activeBrand == null)
            {
                activeBrand = Branding.CurrentBrand;
            }

            if (User.OneDriveAccessToken == null)
            {
                throw new MyFlightbookException(Resources.Profile.errNotConfiguredOneDrive);
            }

            if (od == null)
            {
                od = new OneDrive(User.OneDriveAccessToken);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                WriteZipOfImagesToStream(ms, activeBrand);
                return(await od.PutFileDirect(BackupImagesFilename(activeBrand), ms, "application/zip").ConfigureAwait(true));
            }
        }
Пример #15
0
        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 async Task<OneDrive.ODItem> GetItemsFromSelectionAsync(OneDrive.ODConnection connection = null)
 {
     if (null == connection)
     {
         connection = new OneDrive.ODConnection("https://api.onedrive.com/v1.0", new OAuthTicket(AccessToken, DateTimeOffset.MaxValue));
     }
     var parts = this.SelectionId.Split('.');
     var bundleID = parts[2];
     return await connection.GetItemAsync(new OneDrive.ODItemReference { Id = bundleID }, OneDrive.ItemRetrievalOptions.Default);
 }
Пример #17
0
        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:
                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.OneDrive:
                fileUploader = new OneDrive(Program.UploadersConfig.OneDriveOAuth2Info);
                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:
                int index;

                if (Info.TaskSettings.OverrideFTP)
                {
                    index = Info.TaskSettings.FTPIndex.BetweenOrDefault(0, Program.UploadersConfig.FTPAccountList.Count - 1);
                }
                else
                {
                    index = Program.UploadersConfig.GetFTPIndex(Info.DataType);
                }

                FTPAccount account = Program.UploadersConfig.FTPAccountList.ReturnIfValidIndex(index);

                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.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
                    {
                        StopRequested = 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.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
                };
                break;

            case FileDestination.Pushbullet:
                fileUploader = new Pushbullet(Program.UploadersConfig.PushbulletSettings);
                break;

            case FileDestination.MediaCrush:
                fileUploader = new MediaCrushUploader();
                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;
            }

            if (fileUploader != null)
            {
                PrepareUploader(fileUploader);
                return(fileUploader.Upload(stream, fileName));
            }

            return(null);
        }
Пример #18
0
        /// <summary>
        /// Backup the watch items to OneDrive
        /// </summary>
        /// <returns></returns>
        public async Task <bool> Backup()
        {
            try
            {
                string CompressedFile = "pebble_time_manager_backup.zip";

                // Retrieve files to compress
                IReadOnlyList <IStorageFile> filesToCompress = await LocalStorage.Files();

                // Created new file to store compressed files
                //This will create a file under the selected folder in the name   “Compressed.zip”

                Windows.Storage.StorageFolder LocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile zipFile = await LocalFolder.CreateFileAsync(CompressedFile, CreationCollisionOption.ReplaceExisting);

                using (MemoryStream zipMemoryStream = new MemoryStream())
                {
                    // Create zip archive
                    using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Create))
                    {
                        // For each file to compress...
                        foreach (StorageFile fileToCompress in filesToCompress)
                        {
                            if (fileToCompress.Name != CompressedFile)
                            {
                                //Read the contents of the file
                                byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(fileToCompress));
                                // Create a zip archive entry
                                ZipArchiveEntry entry = zipArchive.CreateEntry(fileToCompress.Name);
                                // And write the contents to it
                                using (Stream entryStream = entry.Open())
                                {
                                    await entryStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                            }
                        }
                    }

                    using (IRandomAccessStream zipStream = await zipFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        // Write compressed data from memory to file
                        using (Stream outstream = zipStream.AsStreamForWrite())
                        {
                            byte[] buffer = zipMemoryStream.ToArray();
                            outstream.Write(buffer, 0, buffer.Length);
                            outstream.Flush();
                        }
                    }
                }

                //Backup to OneDrive
                await OneDrive.UploadFileAsync("Backup", CompressedFile);

                System.Diagnostics.Debug.WriteLine("Backup: " + CompressedFile);

                //Remove zip file
                await LocalStorage.Delete(CompressedFile);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine("Backup exception: " + exp.Message);
                return(false);
            }

            return(true);
        }
 /// <summary>
 /// Initializes the singleton application object.  This is the first line of authored code
 /// executed, and as such is the logical equivalent of main() or WinMain().
 /// </summary>
 public App()
 {
     this.InitializeComponent();
     oneDrive         = new OneDrive();
     this.Suspending += OnSuspending;
 }
Пример #20
0
        public static void Main(string[] args)
        {
            CloudRail.AppKey = "[Your Cloudrail Key]";

            int port = 8082;

            String serviceName = SelectService();

            Box box = new Box(
                new LocalReceiver(port),
                "[Box Client Identifier]",
                "[Box Client Secret]",
                "http://localhost:" + port + "/",
                "someState"
                );

            Dropbox dropbox = new Dropbox(
                new LocalReceiver(port),
                "[Dropbox Client Identifier]",
                "[Dropbox Client Secret]",
                "http://localhost:" + port + "/",
                "someState"
                );

            Egnyte egnyte = new Egnyte(
                new LocalReceiver(port),
                "[Your Egnyte Domain]",
                "[Your Egnyte API Key]",
                "[Your Egnyte Shared Secret]",
                "http://localhost:" + port + "/",
                "someState"
                );

            GoogleDrive googledrive = new GoogleDrive(
                new LocalReceiver(port),
                "[Google Drive Client Identifier]",
                "",
                "http://localhost:" + port + "/",
                "someState"
                );

            OneDrive onedrive = new OneDrive(
                new LocalReceiver(port),
                "[OneDrive Client Identifier]",
                "[OneDrive Client Secret]",
                "http://localhost:" + port + "/",
                "someState"
                );

            OneDriveBusiness onedrivebusiness = new OneDriveBusiness(
                new LocalReceiver(port),
                "[OneDrive Business Client Identifier]",
                "[OneDrive Business Client Secret]",
                "http://localhost:" + port + "/",
                "someState"
                );

            PCloud pCloud = new PCloud(new LocalReceiver(port),
                                       "[pCloud Client Identifier]",
                                       "[pCloud Client Secret]",
                                       "http://localhost:" + port + "/",
                                       "someState");

            service = null;
            switch (serviceName)
            {
            case "1":
                Console.WriteLine("Selected Service: Box");
                service = box;
                break;

            case "2":
                Console.WriteLine("Selected Service: Dropbox");
                service = dropbox;
                break;

            case "3":
                Console.WriteLine("Selected Service: Egnyte");
                service = egnyte;
                break;

            case "4":
                Console.WriteLine("Selected Service: Google Drive");
                service = googledrive;
                break;

            case "5":
                Console.WriteLine("Selected Service: Onedrive");
                service = onedrive;
                break;

            case "6":
                Console.WriteLine("Selected Service: Onedrive for business");
                service = onedrivebusiness;
                break;

            case "7":
                Console.WriteLine("Selected Service: pCloud");
                service = pCloud;
                break;
            }


            Login();
            ShowPath();
            GetNextUserCommand();
        }
Пример #21
0
        public JsonResult Save(Task task, FTP ftp, Models.SyncBackup.Tasks.WebDav webDav, OneDrive oneDrive, IDictionary <string, IgnoreFileOrFolders> ignr = null)
        {
            #region Демо режим
            if (Platform.IsDemo)
            {
                return(Json(new Text("Операция недоступна в демо-режиме")));
            }
            #endregion

            #region Проверка данных
            if (string.IsNullOrWhiteSpace(task.Description))
            {
                return(Json(new Text("Имя задания не может быть пустым")));
            }

            if (string.IsNullOrWhiteSpace(task.Whence))
            {
                return(Json(new Text("Локальный каталог не может быть пустым")));
            }

            if (string.IsNullOrWhiteSpace(task.Where))
            {
                return(Json(new Text("Удаленный каталог не может быть пустым")));
            }

            switch (task.TypeSunc)
            {
            case TypeSunc.SFTP:
            case TypeSunc.FTP:
            {
                if (string.IsNullOrWhiteSpace(ftp.HostOrIP) || string.IsNullOrWhiteSpace(ftp.Login) || (task.Id == 0 && string.IsNullOrWhiteSpace(ftp.Passwd)))
                {
                    return(Json(new Text("Настройки 'FTP/SFTP' имеют недопустимое значение")));
                }
                break;
            }

            case TypeSunc.WebDav:
            {
                if (string.IsNullOrWhiteSpace(webDav.url) || string.IsNullOrWhiteSpace(webDav.Login) || (task.Id == 0 && string.IsNullOrWhiteSpace(webDav.Passwd)))
                {
                    return(Json(new Text("Настройки 'WebDav' имеют недопустимое значение")));
                }
                break;
            }

            case TypeSunc.OneDrive:
            {
                if (string.IsNullOrWhiteSpace(oneDrive.ApplicationId) || (task.Id == 0 && string.IsNullOrWhiteSpace(oneDrive.RefreshToken)))
                {
                    return(Json(new Text("Настройки 'OneDrive' имеют недопустимое значение")));
                }
                break;
            }
            }
            #endregion

            // Уленный сервер
            task.FTP      = ftp;
            task.WebDav   = webDav;
            task.OneDrive = oneDrive;

            // Новое задание
            if (task.Id == 0)
            {
                // Проверка данных AES256
                if (task.EncryptionAES && string.IsNullOrWhiteSpace(task.PasswdAES))
                {
                    return(Json(new Text("Пароль для шифрования файлов не может быть пустым")));
                }

                // Добовляем в базу
                coreDB.SyncBackup_Tasks.Add(task);

                // Сохраняем базу
                coreDB.SaveChanges();

                // Список игнорируемых файлов и папок
                coreDB.SyncBackup_Task_IgnoreFileOrFolders.AddRange(task.Id, ignr, out _);

                // Сохраняем базу
                coreDB.SaveChanges();

                //
                Trigger.OnCreate((task.Id, -1));

                // Отдаем Id записи в базе
                return(Json(new RewriteToId(task.Id)));
            }

            // Старое задание
            else
            {
                // Поиск задания
                if (coreDB.SyncBackup_Tasks.FindAndInclude(task.Id) is var FindTask && FindTask == null)
                {
                    return(Json(new Text("Задание не найдено")));
                }

                #region Используем старый пароль для шифрования файлов
                if (task.EncryptionAES)
                {
                    if (string.IsNullOrWhiteSpace(task.PasswdAES))
                    {
                        if (!string.IsNullOrWhiteSpace(FindTask.PasswdAES))
                        {
                            task.PasswdAES = FindTask.PasswdAES;
                        }
                        else
                        {
                            return(Json(new Text("Пароль для шифрования файлов не может быть пустым")));
                        }
                    }
                }
                #endregion

                #region Используем старый пароль для 'SFTP/FTP/WebDav/OneDrive'
                switch (task.TypeSunc)
                {
                case TypeSunc.SFTP:
                case TypeSunc.FTP:
                {
                    if (string.IsNullOrWhiteSpace(task.FTP.Passwd))
                    {
                        if (!string.IsNullOrWhiteSpace(FindTask.FTP.Passwd))
                        {
                            task.FTP.Passwd = FindTask.FTP.Passwd;
                        }
                        else
                        {
                            return(Json(new Text("Пароль для 'FTP/SFTP' не может быть пустым")));
                        }
                    }
                    break;
                }

                case TypeSunc.WebDav:
                {
                    if (string.IsNullOrWhiteSpace(task.WebDav.Passwd))
                    {
                        if (!string.IsNullOrWhiteSpace(FindTask.WebDav.Passwd))
                        {
                            task.WebDav.Passwd = FindTask.WebDav.Passwd;
                        }
                        else
                        {
                            return(Json(new Text("Пароль для 'WebDav' не может быть пустым")));
                        }
                    }
                    break;
                }

                case TypeSunc.OneDrive:
                {
                    if (string.IsNullOrWhiteSpace(task.OneDrive.RefreshToken))
                    {
                        if (!string.IsNullOrWhiteSpace(FindTask.OneDrive.RefreshToken))
                        {
                            task.OneDrive.RefreshToken = FindTask.OneDrive.RefreshToken;
                        }
                        else
                        {
                            return(Json(new Text("Пароль для 'OneDrive' не может быть пустым")));
                        }
                    }
                    break;
                }
                }
                #endregion

                // Обновляем параметры задания
                CommonModels.Update(FindTask, task);

                // Удаляем список игнорируемых файлов
                coreDB.SyncBackup_Task_IgnoreFileOrFolders.RemoveAll(i => i.TaskId == task.Id);

                // Добовляем список игнорируемых файлов
                coreDB.SyncBackup_Task_IgnoreFileOrFolders.AddRange(task.Id, ignr, out _);

                // Обновляем кеш
                FindTask.CacheExpires = DateTime.Now.AddDays(12);

                // Сохраняем базу
                coreDB.SaveChanges();

                //
                Trigger.OnChange((task.Id, -1));

                // Отдаем результат
                return(Json(new Text("Задание сохранено")));
            }
        }
Пример #22
0
 public JsonResult Task(Task tk, FTP ftp, Models.SyncBackup.Tasks.WebDav webDav, OneDrive oneDrive)
 {
     return(new SyncBackupToTaskController().Save(tk, ftp, webDav, oneDrive));
 }
Пример #23
0
 /// <summary>
 /// Ошибка подключения
 /// </summary>
 /// <param name="_typeSunc">Тип синхронизации</param>
 /// <param name="_ftpConf">Конфигурация удаленого сервера 'ftp/sftp'</param>
 /// <param name="_webDavConf">Конфигурация удаленого сервера 'WebDav'</param>
 /// <param name="_response">Ответ клиента или ошибка try</param>
 public void Connect(TypeSunc _typeSunc, FTP _ftpConf, Models.SyncBackup.Tasks.WebDav _webDavConf, OneDrive oneDriveConf, object _response)
 {
     db.Add(new BaseItem()
     {
         MethodName      = "Connect",
         Response        = _response,
         ArgNameAndValue = new Connect()
         {
             ftpConf      = _ftpConf,
             typeSunc     = _typeSunc,
             webDavConf   = _webDavConf,
             oneDriveConf = oneDriveConf
         }
     });
 }
Пример #24
0
        /// <summary>
        /// Создать подключение с удаленым сервером
        /// </summary>
        /// <param name="_typeSunc">Тип синхронизации</param>
        /// <param name="ftpConf">Конфигурация удаленого сервера 'ftp/sftp'</param>
        /// <param name="webDavConf">Конфигурация удаленого сервера 'WebDav'</param>
        /// <param name="oneDriveConf">Конфигурация удаленого сервера 'OneDrive'</param>
        /// <param name="report">Класс для создания отчета ошибок синхронизации</param>
        public RemoteServer(TypeSunc _typeSunc, FTP ftpConf, Models.SyncBackup.Tasks.WebDav webDavConf, OneDrive oneDriveConf, Report _report, out string NewRefreshTokenToOneDrive)
        {
            NewRefreshTokenToOneDrive = null;

            try
            {
                typeSunc           = _typeSunc;
                report             = _report;
                webDavConfToReport = webDavConf;
                switch (typeSunc)
                {
                case TypeSunc.SFTP:
                {
                    sftp = new SftpClient(ftpConf.HostOrIP, ftpConf.GetToPort(_typeSunc), ftpConf.Login, ftpConf.Passwd);
                    sftp.Connect();
                    break;
                }

                case TypeSunc.FTP:
                {
                    try
                    {
                        // create an FTP client
                        ftp = new FtpClient(ftpConf.HostOrIP, ftpConf.GetToPort(_typeSunc), ftpConf.Login, ftpConf.Passwd);

                        // begin connecting to the server
                        ftp.Connect();
                    }
                    catch
                    {
                        ftp = new FtpClient(ftpConf.HostOrIP, ftpConf.GetToPort(_typeSunc), ftpConf.Login, ftpConf.Passwd);
                        ftp.EncryptionMode       = FtpEncryptionMode.Explicit;
                        ftp.SslProtocols         = SslProtocols.Tls;
                        ftp.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
                        ftp.Connect();

                        void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e)
                        {
                            // add logic to test if certificate is valid here
                            e.Accept = true;
                        }
                    }
                    break;
                }

                case TypeSunc.WebDav:
                {
                    webDav = new WebDavClient(new WebDavClientParams
                        {
                            BaseAddress           = new Uri(webDavConf.url),
                            Credentials           = new NetworkCredential(webDavConf.Login, webDavConf.Passwd),
                            PreAuthenticate       = true,
                            UseDefaultCredentials = false      // Yandex.Disk на linux так работает
                        });
                    break;
                }

                case TypeSunc.OneDrive:
                {
                    /// <summary>
                    /// Version 2.0.1.0
                    /// https://github.com/KoenZomers/OneDriveAPI
                    /// </summary>
                    oneDrive = new OneDriveGraphApi(oneDriveConf.ApplicationId);
                    oneDrive.AuthenticateUsingRefreshToken(oneDriveConf.RefreshToken).Wait();

                    if (!string.IsNullOrWhiteSpace(oneDrive.AccessToken.RefreshToken))
                    {
                        IsConnectedToOneDrive     = true;
                        NewRefreshTokenToOneDrive = oneDrive.AccessToken.RefreshToken;
                    }
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                report.Connect(_typeSunc, ftpConf, webDavConf, oneDriveConf, ex.ToString());
                ConnectionError = true;
            }
        }
Пример #25
0
        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();
        }
        public async Task<ODPermission> CreateSharingLinkAsync(ODItemReference itemReference, OneDrive.Facets.LinkType type)
        {
            if (!itemReference.IsValid())
                throw new ArgumentException("itemReference");

            Uri serviceUri = UriForItemReference(itemReference, ApiConstants.CreateLinkAction);
            var request = await CreateHttpRequestAsync(serviceUri, ApiConstants.HttpPost);

            var postBody = new
            {
                type = type
            };

            await SerializeObjectToRequestBody(postBody, request);
            return await DataModelForRequest<ODPermission>(request);
        }