Пример #1
0
        public static NextcloudClient.NextcloudClient GetClient()
        {
            if (_client != null)
            {
                return(_client);
            }

            if (!string.IsNullOrEmpty(SettingsService.Instance.Settings.ServerAddress) &&
                !string.IsNullOrEmpty(SettingsService.Instance.Settings.Username))
            {
                var vault       = new PasswordVault();
                var credentials = vault.Retrieve(
                    SettingsService.Instance.Settings.ServerAddress,
                    SettingsService.Instance.Settings.Username
                    );

                if (credentials != null)
                {
                    _client = new NextcloudClient.NextcloudClient(
                        credentials.Resource,
                        credentials.UserName,
                        credentials.Password
                        );
                }
            }

            SettingsService.Instance.Settings.PropertyChanged += (sender, args) =>
            {
                if (
                    string.IsNullOrEmpty(SettingsService.Instance.Settings.ServerAddress) ||
                    string.IsNullOrEmpty(SettingsService.Instance.Settings.Username)
                    )
                {
                    return;
                }

                var vault       = new PasswordVault();
                var credentials = vault.Retrieve(
                    SettingsService.Instance.Settings.ServerAddress,
                    SettingsService.Instance.Settings.Username
                    );

                if (credentials == null)
                {
                    return;
                }

                _client = new NextcloudClient.NextcloudClient(
                    credentials.Resource,
                    credentials.UserName,
                    credentials.Password
                    );
            };

            return(_client);
        }
Пример #2
0
        static async Task MainAsync()
        {
            //var xc = new WebDavClass();
            //await xc.RunAsync();

            string cloudUsr = "******";
            string cloudPw  = "******";
            string url      = @"https://nextcloud.**********.gr/remote.php/webdav/";

            var nccl = new NextcloudClient.NextcloudClient(url, cloudUsr, cloudPw);

            var fff = await nccl.List("/");


            string pathToSave = @"c:\temp\nextcloud\";
            string docToSave  = $"tmp432534534.docx";


            try
            {
                //    var cts = new CancellationTokenSource();
                //    IProgress<WebDavProgress> progress = new Progress<WebDavProgress>();

                FileStream dataToUpload = File.OpenRead(pathToSave + docToSave);
                dataToUpload.Position = 0;
                //var rr = await nccl.UploadWithProgressAsync("/", dataToUpload, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", progress, cts.Token);
                //var rr = await nccl.Upload("", "234fcdsg343e.docx", dataToUpload);
                //var rr = await nccl.Upload($"/{docToSave}", dataToUpload);

                var info = await nccl.GetResourceInfo("/", docToSave);
            }
            catch (ResponseError e2)
            {
                //ResponseErrorHandlerService.HandleException(e2);
            }

            Console.ReadLine();
        }
Пример #3
0
        private async Task SychronizeFolder(ResourceInfo resourceInfo)
        {
            if (resourceInfo == null)
            {
                return;
            }

            var           syncInfo = SyncDbUtils.GetFolderSyncInfoByPath(resourceInfo.Path);
            StorageFolder folder;

            try
            {
                Task <ContentDialogResult> firstRunDialog = null;
                if (syncInfo == null)
                {
                    // try to Get parent or initialize
                    syncInfo = SyncDbUtils.GetFolderSyncInfoBySubPath(resourceInfo.Path);

                    if (syncInfo == null)
                    {
                        // Initial Sync
                        syncInfo = new FolderSyncInfo()
                        {
                            Path = resourceInfo.Path
                        };

                        var folderPicker = new FolderPicker()
                        {
                            SuggestedStartLocation = PickerLocationId.Desktop
                        };

                        folderPicker.FileTypeFilter.Add(".txt");
                        StorageFolder newFolder = await folderPicker.PickSingleFolderAsync();

                        if (newFolder == null)
                        {
                            return;
                        }

                        StorageApplicationPermissions.FutureAccessList.AddOrReplace(syncInfo.AccessListKey, newFolder);
                        IReadOnlyList <IStorageItem> subElements = await newFolder.GetItemsAsync();

                        NextcloudClient.NextcloudClient client = await ClientService.GetClient();

                        var remoteElements = await client.List(resourceInfo.Path);

                        if (subElements.Count > 0 && remoteElements.Count > 0)
                        {
                            var dialogNotEmpty = new ContentDialog
                            {
                                Title   = _resourceLoader.GetString("SyncFoldersNotEmptyWarning"),
                                Content = new TextBlock()
                                {
                                    Text         = _resourceLoader.GetString("SyncFoldersNotEmptyWarningDetail"),
                                    TextWrapping = TextWrapping.WrapWholeWords,
                                    Margin       = new Thickness(0, 20, 0, 0)
                                },
                                PrimaryButtonText   = _resourceLoader.GetString("OK"),
                                SecondaryButtonText = _resourceLoader.GetString("Cancel")
                            };

                            var dialogResult = await _dialogService.ShowAsync(dialogNotEmpty);

                            if (dialogResult != ContentDialogResult.Primary)
                            {
                                return;
                            }
                        }

                        folder = newFolder;
                        SyncDbUtils.SaveFolderSyncInfo(syncInfo);
                        StartDirectoryListing(); // This is just to update the menu flyout - maybe there is a better way

                        var dialog = new ContentDialog
                        {
                            Title   = _resourceLoader.GetString("SyncStarted"),
                            Content = new TextBlock()
                            {
                                Text         = _resourceLoader.GetString("SyncStartedDetail"),
                                TextWrapping = TextWrapping.WrapWholeWords,
                                Margin       = new Thickness(0, 20, 0, 0)
                            },
                            PrimaryButtonText = _resourceLoader.GetString("OK")
                        };
                        firstRunDialog = _dialogService.ShowAsync(dialog);
                    }
                    else
                    {
                        string        subPath    = resourceInfo.Path.Substring(syncInfo.Path.Length);
                        StorageFolder tempFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(syncInfo.AccessListKey);

                        foreach (string foldername in subPath.Split('/'))
                        {
                            if (foldername.Length > 0)
                            {
                                tempFolder = await tempFolder.GetFolderAsync(foldername);
                            }
                        }
                        folder = tempFolder;
                    }
                }
                else
                {
                    folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(syncInfo.AccessListKey);

                    // TODO catch exceptions
                }

                SyncService service = new SyncService(folder, resourceInfo, syncInfo);
                await service.StartSync();

                if (firstRunDialog != null)
                {
                    await firstRunDialog;
                }
            }
            catch (Exception e)
            {
                // ERROR Maybe AccessList timed out.
                Debug.WriteLine(e.Message);
            }
        }
Пример #4
0
        private async Task Download(ResourceInfo resourceInfo, NextcloudClient.NextcloudClient client, StorageFolder folder)
        {
            if (resourceInfo.ContentType == "dav/directory")
            {
                ResourceInfo = new ResourceInfo
                {
                    Name        = resourceInfo.Name + ".zip",
                    ContentType = "application/zip",
                    Path        = resourceInfo.Path
                };
            }
            else
            {
                ResourceInfo = resourceInfo;
            }

            var savePicker = new FileSavePicker();

            savePicker.FileTypeChoices.Add(ResourceInfo.ContentType, new List <string> {
                Path.GetExtension(ResourceInfo.Name)
            });
            savePicker.SuggestedFileName = ResourceInfo.Name;

            StorageFile localFile;

            if (folder != null)
            {
                try
                {
                    localFile = await folder.CreateFileAsync(
                        savePicker.SuggestedFileName,
                        CreationCollisionOption.GenerateUniqueName);
                }
                catch (FileNotFoundException)
                {
                    //this.textBlock.Text = "Error " + ex;
                    return;
                }
            }
            else
            {
                localFile = await savePicker.PickSaveFileAsync();
            }
            if (localFile == null)
            {
                return;
            }

            _currentFile = localFile;

            // Prevent updates to the remote version of the file until
            // we finish making changes and call CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(localFile);

            try
            {
                IProgress <WebDavProgress> progress = new Progress <WebDavProgress>(ProgressHandler);

                using (var randomAccessStream = await localFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var targetStream = randomAccessStream.AsStreamForWrite();

                    switch (resourceInfo.ContentType)
                    {
                    case "dav/directory":
                        await client.DownloadDirectoryAsZip(ResourceInfo.Path, targetStream, progress, _cts.Token);

                        break;

                    default:
                        await client.Download(ResourceInfo.Path + "/" + ResourceInfo.Name, targetStream, progress, _cts.Token);

                        break;
                    }
                }
            }
            catch (ResponseError e2)
            {
                ResponseErrorHandlerService.HandleException(e2);
            }

            // Let Windows know that we're finished changing the file so
            // the other app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
            var status = await CachedFileManager.CompleteUpdatesAsync(localFile);

            if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
            {
                //this.textBlock.Text = "Path " + file.Name + " was saved.";
            }
            else
            {
                //this.textBlock.Text = "Path " + file.Name + " couldn't be saved.";
            }
        }
Пример #5
0
 public static void Reset()
 {
     _client = null;
 }
Пример #6
0
        public static async Task <NextcloudClient.NextcloudClient> GetClient()
        {
            if (_client != null)
            {
                return(_client);
            }

            if (!string.IsNullOrEmpty(SettingsService.Default.Value.LocalSettings.ServerAddress) &&
                !string.IsNullOrEmpty(SettingsService.Default.Value.LocalSettings.Username))
            {
                var vault = new PasswordVault();

                IReadOnlyList <PasswordCredential> credentialList = null;
                try
                {
                    credentialList = vault.FindAllByResource(SettingsService.Default.Value.LocalSettings.ServerAddress);
                }
                catch
                {
                    // ignored
                }

                var credential = credentialList?.FirstOrDefault(item => item.UserName.Equals(SettingsService.Default.Value.LocalSettings.Username));

                if (credential == null)
                {
                    return(null);
                }

                credential.RetrievePassword();

                try
                {
                    var response = await NextcloudClient.NextcloudClient.GetServerStatus(credential.Resource, SettingsService.Default.Value.LocalSettings.IgnoreServerCertificateErrors);

                    if (response == null)
                    {
                        await ShowServerAddressNotFoundMessage(credential.Resource);

                        return(null);
                    }
                }
                catch
                {
                    await ShowServerAddressNotFoundMessage(credential.Resource);

                    return(null);
                }

                _client = new NextcloudClient.NextcloudClient(
                    credential.Resource,
                    credential.UserName,
                    credential.Password
                    )
                {
                    IgnoreServerCertificateErrors =
                        SettingsService.Default.Value.LocalSettings.IgnoreServerCertificateErrors
                };
            }

            SettingsService.Default.Value.LocalSettings.PropertyChanged += async(sender, args) =>
            {
                if (_client != null && args.PropertyName == "IgnoreServerCertificateErrors")
                {
                    _client.IgnoreServerCertificateErrors =
                        SettingsService.Default.Value.LocalSettings.IgnoreServerCertificateErrors;
                }

                if (
                    string.IsNullOrEmpty(SettingsService.Default.Value.LocalSettings.ServerAddress) ||
                    string.IsNullOrEmpty(SettingsService.Default.Value.LocalSettings.Username)
                    )
                {
                    _client = null;
                    return;
                }

                var vault = new PasswordVault();

                IReadOnlyList <PasswordCredential> credentialList = null;
                try
                {
                    credentialList = vault.FindAllByResource(SettingsService.Default.Value.LocalSettings.ServerAddress);
                }
                catch
                {
                    // ignored
                }

                var credential = credentialList?.FirstOrDefault(item => item.UserName.Equals(SettingsService.Default.Value.LocalSettings.Username));

                if (credential == null)
                {
                    _client = null;
                    return;
                }

                credential.RetrievePassword();

                try
                {
                    var response = await NextcloudClient.NextcloudClient.GetServerStatus(credential.Resource, SettingsService.Default.Value.LocalSettings.IgnoreServerCertificateErrors);

                    if (response == null)
                    {
                        _client = null;
                        await ShowServerAddressNotFoundMessage(credential.Resource);

                        return;
                    }
                }
                catch
                {
                    _client = null;
                    await ShowServerAddressNotFoundMessage(credential.Resource);

                    return;
                }

                _client = new NextcloudClient.NextcloudClient(
                    credential.Resource,
                    credential.UserName,
                    credential.Password
                    )
                {
                    IgnoreServerCertificateErrors =
                        SettingsService.Default.Value.LocalSettings.IgnoreServerCertificateErrors
                };
            };

            return(_client);
        }
Пример #7
0
        public async Task <bool> StartSync()
        {
            if (!SyncDbUtils.LockFolderSyncInfo(folderSyncInfo))
            {
                return(false);
            }

            try
            {
                client = await ClientService.GetClient();

                if (client == null)
                {
                    // ERROR
                    throw new Exception("Error creating webdav client");
                }

                int changedCount = 0;
                List <SyncInfoDetail> oldList = SyncDbUtils.GetAllSyncInfoDetails(folderSyncInfo);
                Debug.WriteLine("Sid List before Sync: ");

                foreach (SyncInfoDetail detail in oldList)
                {
                    Debug.WriteLine("Detail: " + detail.ToString());
                }

                var sid        = SyncDbUtils.GetSyncInfoDetail(resourceInfo, folderSyncInfo);
                var errorCount = 0;

                try
                {
                    if (sid == null)
                    {
                        sid = new SyncInfoDetail(folderSyncInfo)
                        {
                            Path     = resourceInfo.Path,
                            FilePath = baseFolder.Path,
                        };

                        SyncDbUtils.SaveSyncInfoDetail(sid);
                    }
                    else
                    {
                        sidList.Remove(sid);
                        sid.Error = null;
                    }

                    changedCount = await SyncFolder(resourceInfo, baseFolder);

                    foreach (SyncInfoDetail detail in oldList)
                    {
                        if (!sidList.Contains(detail) && detail.FilePath.StartsWith(baseFolder.Path))
                        {
                            // The items left here must have been deleted both remotely and locally so the sid is obsolete.
                            SyncDbUtils.DeleteSyncInfoDetail(detail, false);
                            changedCount++;
                        }
                    }
                    errorCount = SyncDbUtils.GetErrorConflictCount(folderSyncInfo);
                }
                catch (Exception e)
                {
                    sid.Error = e.Message;
                    errorCount++;
                }

                SyncDbUtils.SaveSyncInfoDetail(sid);
                List <SyncInfoDetail> newSidList = SyncDbUtils.GetAllSyncInfoDetails(folderSyncInfo);
                Debug.WriteLine("Sid List after Sync: ");

                foreach (SyncInfoDetail detail in newSidList)
                {
                    Debug.WriteLine("Detail: " + detail.ToString());
                }

                ToastNotificationService.ShowSyncFinishedNotification(folderSyncInfo.Path, changedCount, errorCount);
                return(errorCount == 0);
            }
            finally
            {
                SyncDbUtils.UnlockFolderSyncInfo(folderSyncInfo);
            }
        }
        public async Task <bool> StartSync()
        {
            if (!SyncDbUtils.LockFolderSyncInfo(_folderSyncInfo))
            {
                return(false);
            }

            try
            {
                _client = await ClientService.GetClient();

                if (_client == null)
                {
                    // ERROR
                    throw new NullReferenceException(_resourceLoader.GetString(ResourceConstants.SyncService_Error_CannotCreateClient));
                }

                var changedCount = 0;
                var oldList      = SyncDbUtils.GetAllSyncInfoDetails(_folderSyncInfo);
                Debug.WriteLine("Sid List before Sync: ");

                foreach (var detail in oldList)
                {
                    Debug.WriteLine("Detail: " + detail);
                }

                var sid        = SyncDbUtils.GetSyncInfoDetail(_resourceInfo, _folderSyncInfo);
                var errorCount = 0;

                try
                {
                    if (sid == null)
                    {
                        sid = new SyncInfoDetail(_folderSyncInfo)
                        {
                            Path     = _resourceInfo.Path,
                            FilePath = _baseFolder.Path,
                        };

                        SyncDbUtils.SaveSyncInfoDetail(sid);
                    }
                    else
                    {
                        _sidList.Remove(sid);
                        sid.Error = null;
                    }

                    changedCount = await SyncFolder(_resourceInfo, _baseFolder);

                    foreach (var detail in oldList)
                    {
                        if (_sidList.Contains(detail) || !detail.FilePath.StartsWith(_baseFolder.Path))
                        {
                            continue;
                        }
                        // The items left here must have been deleted both remotely and locally so the sid is obsolete.
                        SyncDbUtils.DeleteSyncInfoDetail(detail, false);
                        changedCount++;
                    }
                    errorCount = SyncDbUtils.GetErrorConflictCount(_folderSyncInfo);
                }
                catch (Exception e)
                {
                    sid.Error = string.Format(_resourceLoader.GetString("UnexpectedException"), e.Message);
                    errorCount++;
                }

                SyncDbUtils.SaveSyncInfoDetail(sid);
                var newSidList = SyncDbUtils.GetAllSyncInfoDetails(_folderSyncInfo);
                Debug.WriteLine("Sid List after Sync: ");

                foreach (var detail in newSidList)
                {
                    Debug.WriteLine("Detail: " + detail);
                }

                ToastNotificationService.ShowSyncFinishedNotification(_folderSyncInfo.Path, changedCount, errorCount);
                return(errorCount == 0);
            }
            finally
            {
                SyncDbUtils.UnlockFolderSyncInfo(_folderSyncInfo);
            }
        }