Ejemplo n.º 1
0
        public async void EnviarNextCloud(List <IFormFile> files, string Url, string Path, string Folder)
        {
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    using var ms = new MemoryStream();
                    await formFile.CopyToAsync(ms);

                    ms.Seek(0, SeekOrigin.Begin);


                    var clientParams = new WebDavClientParams
                    {
                        BaseAddress = new Uri(Url),
                        Credentials = new NetworkCredential(ConfigurationManager.AppSetting["NextCloud:User"], ConfigurationManager.AppSetting["NextCloud:Password"])
                    };
                    var client = new WebDavClient(clientParams);


                    await client.Mkcol(Folder + "/");

                    await client.Mkcol(Folder + "/" + Path + "/");

                    clientParams.BaseAddress = new Uri(clientParams.BaseAddress + Folder + "/" + Path + "/");
                    client = new WebDavClient(clientParams);

                    await client.PutFile(formFile.FileName, ms); // upload a resource
                }
            }
        }
Ejemplo n.º 2
0
        public async void When_RequestIsSuccessfull_Should_ReturnStatusCode200()
        {
            var client = new WebDavClient().SetWebDavDispatcher(Dispatcher.Mock());
            var response1 = await client.Mkcol("http://example.com/new");
            var response2 = await client.Mkcol(new Uri("http://example.com/new"));
            var response3 = await client.Mkcol("http://example.com/new", new MkColParameters());
            var response4 = await client.Mkcol(new Uri("http://example.com/new"), new MkColParameters());

            Assert.Equal(200, response1.StatusCode);
            Assert.Equal(200, response2.StatusCode);
            Assert.Equal(200, response3.StatusCode);
            Assert.Equal(200, response4.StatusCode);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Создать папку на удаленом сервере
        /// </summary>
        /// <param name="path">Полный путь папки на сервере</param>
        /// <param name="NotReport">Не заносить ошибку в отчет</param>
        public bool CreateDirectory(string path, bool NotReport = false)
        {
            try
            {
                switch (typeSunc)
                {
                case TypeSunc.SFTP:
                {
                    sftp.CreateDirectory(path);
                    return(true);
                }

                case TypeSunc.FTP:
                {
                    ftp.CreateDirectory(path);
                    return(true);
                }

                case TypeSunc.WebDav:
                {
                    var res = webDav.Mkcol(path).Result;
                    if (res.StatusCode == 201)
                    {
                        return(true);
                    }

                    if (!NotReport)
                    {
                        report.Base("CreateDirectory", path, res);
                    }
                    return(createDirectory(path));
                }

                case TypeSunc.OneDrive:
                {
                    oneDrive.GetFolderOrCreate(path).Wait();
                    return(true);
                }
                }
            }
            catch (Exception ex)
            {
                if (!NotReport)
                {
                    report.Base("CreateDirectory", path, ex.ToString());
                }
            }
            return(false);
        }
Ejemplo n.º 4
0
        private void CreateDirectory(string filepath, WebDavClient webDav)
        {
            var pathItems = filepath.Replace("\\", "/").Split('/');
            var path      = "";

            for (int i = 0; i < pathItems.Length; i++)
            {
                path = path + pathItems[i];
                var propParam = new PropfindParameters();
                RetryIfFail(5, () =>
                {
                    var propFind = webDav.PropFind(new Uri($"{webDav.BaseAddress}{path}"), propParam);
                    if (!propFind.IsSuccessful)
                    {
                        if (propFind.StatusCode != 404)
                        {
                            throw new ApplicationException($"Unable read file props: --> {propFind.StatusCode} {propFind.Description}");
                        }

                        var folder = webDav.Mkcol(new Uri($"{webDav.BaseAddress}{path}"));
                        if (!folder.IsSuccessful)
                        {
                            throw new ApplicationException($"Unable create folder: --> {folder.StatusCode} {folder.Description}");
                        }
                    }
                    return(propFind);
                });
                path = path + "/";
            }
        }
        public async Task MakeCollection(string folderPath)
        {
            using (var client = new WebDavClient(_webDavClientParams))
            {
                var pathFolders = folderPath.Split("/");
                var url         = "";

                foreach (var folder in pathFolders)
                {
                    url = url.Equals("") ? folder : $"{url}/{folder}/";

                    var res = await client.Mkcol(url);

                    if (res.StatusCode == 200 ||
                        res.StatusCode == 201 ||
                        res.StatusCode == 405)
                    {
                        continue;
                    }

                    var msg = $"Could not create folder {folderPath}! ({res.StatusCode} {res.Description})";

                    _logger.LogError(msg);
                    throw new NextCloudException(msg);
                }
            }
        }
 /// <summary>
 /// Creates a Directory at the given destination Uri and
 /// returns wheter the creation was successfull
 /// </summary>
 /// <param name="dstUri"></param>
 /// <returns></returns>
 public IRemoteProperty CreateDirectory(CancellationToken cancleToken, string dstUri)
 {
     dstUri = _config.Remote.RemoteFolderPath.RemoveTailingSlashes() + dstUri;
     try
     {
         _logger.Debug("Creating remote directory " + dstUri);
         WebDavResponse res = _webDavClient.Mkcol(dstUri, new MkColParameters()
         {
             CancellationToken = cancleToken,
         }).Result;
         if (res.IsSuccessful)
         {
             _logger.Debug("Creating remote directory " + dstUri + " was successfull");
             return(GetProperty(dstUri, _webDavClient));
         }
         else
         {
             _logger.Error("Creating remote directory " + dstUri + " failed!");
         }
     } catch (Exception exc)
     {
         _logger.Error("Unhandled exception occured while creation remote directory: " + dstUri, exc);
     }
     return(null);
 }
Ejemplo n.º 7
0
        public async void When_RequestIsSuccessfull_Should_ReturnStatusCode200()
        {
            var client    = new WebDavClient().SetWebDavDispatcher(Dispatcher.Mock());
            var response1 = await client.Mkcol("http://example.com/new");

            var response2 = await client.Mkcol(new Uri("http://example.com/new"));

            var response3 = await client.Mkcol("http://example.com/new", new MkColParameters());

            var response4 = await client.Mkcol(new Uri("http://example.com/new"), new MkColParameters());

            Assert.Equal(200, response1.StatusCode);
            Assert.Equal(200, response2.StatusCode);
            Assert.Equal(200, response3.StatusCode);
            Assert.Equal(200, response4.StatusCode);
        }
Ejemplo n.º 8
0
        public async void When_RequestIsFailed_Should_ReturnStatusCode500()
        {
            var client   = new WebDavClient().SetWebDavDispatcher(Dispatcher.MockFaulted());
            var response = await client.Mkcol("http://example.com/new");

            Assert.Equal(500, response.StatusCode);
        }
Ejemplo n.º 9
0
        public async void When_IsCalledWithCancellationToken_Should_SendRequestWithIt()
        {
            var cts = new CancellationTokenSource();
            var dispatcher = Dispatcher.Mock();
            var client = new WebDavClient().SetWebDavDispatcher(dispatcher);

            await client.Mkcol("http://example.com/new", new MkColParameters { CancellationToken = cts.Token });
            await dispatcher.Received(1)
                .Send(Arg.Any<Uri>(), WebDavMethod.Mkcol, Arg.Is<RequestParameters>(x => !x.Headers.Any() && x.Content == null), cts.Token);
        }
Ejemplo n.º 10
0
        public async void When_IsCalledWithLockToken_Should_SetIfHeader()
        {
            var requestUri = new Uri("http://example.com/new");
            var dispatcher = Dispatcher.Mock();
            var client     = new WebDavClient().SetWebDavDispatcher(dispatcher);

            await client.Mkcol(requestUri, new MkColParameters { LockToken = "urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4" });

            await dispatcher.Received(1)
            .Send(requestUri, WebDavMethod.Mkcol, Arg.Is(Predicates.CompareHeader("If", "(<urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4>)")), CancellationToken.None);
        }
Ejemplo n.º 11
0
        public async void When_IsCalledWithDefaultArguments_Should_SendMkcolRequest()
        {
            var requestUri = new Uri("http://example.com/new");
            var dispatcher = Dispatcher.Mock();
            var client = new WebDavClient().SetWebDavDispatcher(dispatcher);

            await dispatcher.DidNotReceiveWithAnyArgs().Send(requestUri, Arg.Any<HttpMethod>(), new RequestParameters(), CancellationToken.None);
            await client.Mkcol(requestUri);
            await dispatcher.Received(1)
                .Send(requestUri, WebDavMethod.Mkcol, Arg.Is<RequestParameters>(x => !x.Headers.Any() && x.Content == null), CancellationToken.None);
        }
Ejemplo n.º 12
0
        public async void When_IsCalledWithCancellationToken_Should_SendRequestWithIt()
        {
            var cts        = new CancellationTokenSource();
            var dispatcher = Dispatcher.Mock();
            var client     = new WebDavClient().SetWebDavDispatcher(dispatcher);

            await client.Mkcol("http://example.com/new", new MkColParameters { CancellationToken = cts.Token });

            await dispatcher.Received(1)
            .Send(Arg.Any <Uri>(), WebDavMethod.Mkcol, Arg.Is <RequestParameters>(x => !x.Headers.Any() && x.Content == null), cts.Token);
        }
Ejemplo n.º 13
0
        public async void When_IsCalledWithLockToken_Should_SetIfHeader()
        {
            var requestUri = new Uri("http://example.com/new");
            var dispatcher = Dispatcher.Mock();
            var client = new WebDavClient().SetWebDavDispatcher(dispatcher);

            await dispatcher.DidNotReceiveWithAnyArgs().Send(requestUri, Arg.Any<HttpMethod>(), new RequestParameters(), CancellationToken.None);
            await client.Mkcol(requestUri, new MkColParameters { LockToken = "urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4" });
            await dispatcher.Received(1)
                .Send(requestUri, WebDavMethod.Mkcol, Arg.Is(Predicates.CompareHeader("If", "(<urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4>)")), CancellationToken.None);
        }
Ejemplo n.º 14
0
        public async void When_IsCalledWithDefaultArguments_Should_SendMkcolRequest()
        {
            var requestUri = new Uri("http://example.com/new");
            var dispatcher = Dispatcher.Mock();
            var client     = new WebDavClient().SetWebDavDispatcher(dispatcher);

            await client.Mkcol(requestUri);

            await dispatcher.Received(1)
            .Send(requestUri, WebDavMethod.Mkcol, Arg.Is <RequestParameters>(x => !x.Headers.Any() && x.Content == null), CancellationToken.None);
        }
Ejemplo n.º 15
0
        public async Task <OnlineItem> CreateFolderAsync(string relativePath, OnlineItem parent = null)
        {
            // The default relative path is just nothing.
            if (string.IsNullOrEmpty(relativePath))
            {
                throw new ArgumentException("The relative path cannot be null or empty.", nameof(relativePath));
            }
            if (relativePath.StartsWith("/") || relativePath.EndsWith("/"))
            {
                throw new ArgumentException("The relative path cannot start or end with a slash.", nameof(relativePath));
            }

            // Create a new root if it does not exist (this will be the /Share/Guid/ folder.
            if (parent == null)
            {
                parent           = new OnlineItem();
                parent.LocalPath = string.Empty;
                parent.FullPath  = OnlinePathBuilder.ConvertPathToFullUri(_connectionSettings.StorageUri, null);
            }

            OnlineItem currentChild = parent;

            var pathParts = relativePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string pathPart in pathParts)
            {
                currentChild = OnlinePathBuilder.CreateChild(currentChild, pathPart);

                // Create the folder
                _cancellationToken.ThrowIfCancellationRequested();

                var createResponse = await _client.Mkcol(currentChild.FullPath, new MkColParameters { CancellationToken = _cancellationToken }).ConfigureAwait(false);

                if (createResponse.StatusCode != 201 && createResponse.StatusCode != 405) // 405 if maybe a tweak to not check if it exists?
                {
                    throw new Exception($"The folder is not created, code={createResponse.StatusCode}, description={createResponse.Description}");
                }
            }

            return(OnlinePathBuilder.CreateChild(parent, relativePath));
        }
Ejemplo n.º 16
0
        private static async Task TestWebDav()
        {
            using (var webDavClient = new WebDavClient(new WebDavClientParams {
                BaseAddress = new Uri("http://mywebdav:88/")
            }))
            {
                await webDavClient.Copy("1.txt", "_2.txt");

                await webDavClient.Move("http://mywebdav:88/_2.txt", "2.txt");

                await webDavClient.Mkcol("http://mywebdav:88/mydir");

                await webDavClient.PutFile("http://mywebdav:88/mydir/test.txt", File.OpenRead("test.txt"), "text/plain");

                await webDavClient.Move("mydir/test.txt", "http://mywebdav:88/mydir/test_ren.txt");

                await webDavClient.Copy("http://mywebdav:88/mydir/", "http://mywebdav:88/mydir1/");

                await webDavClient.Copy("http://mywebdav:88/mydir/", "http://mywebdav:88/mydir2/", new CopyParameters { ApplyTo = ApplyTo.Copy.ResourceOnly });

                using (var response = await webDavClient.GetRawFile("http://mywebdav:88/mydir/test_ren.txt"))
                    using (var reader = new StreamReader(response.Stream))
                    {
                        var fileOutput = await reader.ReadToEndAsync();

                        Console.WriteLine(fileOutput);
                    }

                await TestPropfind(webDavClient);

                await TestSearch(webDavClient);

                await TestLock(webDavClient);

                await TestPropatch(webDavClient);

                await webDavClient.Delete("http://mywebdav:88/mydir");
            }
        }
Ejemplo n.º 17
0
        public void runSync()
        {
            saveBtn.Sensitive   = false;
            progressBar.Visible = true;

            IWebDavClient _client      = new WebDavClient();
            var           clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri(db.webDavHost),
                Credentials = new NetworkCredential(db.webDavUsername, db.webDavPass)
            };

            _client = new WebDavClient(clientParams);

            Thread t = new Thread(async() => {
                System.Timers.Timer ti = new System.Timers.Timer(200);
                ti.Elapsed            += (delegate {
                    progressBar.Pulse();
                });
                ti.Start();

                var result = await _client.Propfind(db.webDavHost + "/Money");
                if (result.IsSuccessful)
                {
                    bool containsDb = false;
                    foreach (var res in result.Resources)
                    {
                        if (res.Uri.EndsWith("database.mdb")) //Check if we have the database online
                        {
                            containsDb = true;
                            break;
                        }
                    }

                    if (containsDb)
                    {
                        //Let's grab the online version
                        var resultInner = await _client.GetRawFile(db.webDavHost + "/Money/database.mdb");

                        StreamReader reader = new StreamReader(resultInner.Stream);
                        string json         = reader.ReadToEnd();
                        Database oDb        = JsonConvert.DeserializeObject <Database>(json);

                        //Check if modDateTime is newer than current database
                        //if so replace local with online
                        if (oDb.modDateTime < db.modDateTime)
                        {
                            File.WriteAllText(dbPath, json);

                            db  = null;
                            oDb = null;

                            db = new Database(dbPath);
                        }
                        else
                        //Else upload local to online
                        {
                            //First delete the online version
                            var resultInnerInner = await _client.Delete(db.webDavHost + "/Money/database.mdb");

                            if (resultInnerInner.IsSuccessful)
                            {
                                var resultInnerInnerInner = await _client.PutFile(db.webDavHost + "/Money/database.mdb", File.OpenRead(dbPath));

                                if (!resultInnerInnerInner.IsSuccessful)
                                {
                                    Gtk.Application.Invoke(delegate {
                                        new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Failed to upload database. Sync error " + resultInnerInner.StatusCode + " (" + resultInnerInner.Description + ")").Show();
                                    });
                                }
                            }
                            else
                            {
                                Gtk.Application.Invoke(delegate {
                                    new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Failed to delete out-of-sync online database. Sync error " + resultInnerInner.StatusCode + " (" + resultInnerInner.Description + ")").Show();
                                });
                            }
                        }
                        Gtk.Application.Invoke(delegate {
                            db.Save(dbPath);
                            this.Close();
                        });
                    }
                    else
                    {
                        var resultInner = await _client.PutFile(db.webDavHost + "/Money/database.mdb", File.OpenRead(dbPath));

                        if (!resultInner.IsSuccessful)
                        {
                            Gtk.Application.Invoke(delegate {
                                new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Sync error " + resultInner.StatusCode + " (" + resultInner.Description + ")").Show();
                            });
                        }
                        else
                        {
                            Gtk.Application.Invoke(delegate {
                                db.Save(dbPath);
                                this.Close();
                            });
                        }
                    }
                }
                else if (result.StatusCode == 404)
                {
                    var resultInner = await _client.Mkcol("Money");

                    if (resultInner.IsSuccessful)
                    {
                        resultInner = await _client.PutFile(db.webDavHost + "/Money/database.mdb", File.OpenRead(dbPath));

                        if (!resultInner.IsSuccessful)
                        {
                            Gtk.Application.Invoke(delegate {
                                new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Sync error " + resultInner.StatusCode + " (" + resultInner.Description + ")").Show();
                            });
                        }
                        else
                        {
                            Gtk.Application.Invoke(delegate {
                                db.Save(dbPath);
                                this.Close();
                            });
                        }
                    }
                    else
                    {
                        Gtk.Application.Invoke(delegate {
                            new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Sync error " + resultInner.StatusCode + " (" + resultInner.Description + ")").Show();
                        });
                    }
                }
                else
                {
                    Gtk.Application.Invoke(delegate {
                        new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, false, "Sync error " + result.StatusCode + " (" + result.Description + ")").Show();
                    });
                }

                ti.Stop();

                Gtk.Application.Invoke(delegate {
                    progressBar.Visible = false;
                    saveBtn.Sensitive   = true;
                });
            });

            t.Start();
        }
Ejemplo n.º 18
0
        public override async Task <bool> ConfirmAccount()
        {
            var result = await _WebDevClient.Mkcol("KeqingNiuza");

            return(result.IsSuccessful);
        }
Ejemplo n.º 19
0
 public async void When_RequestIsFailed_Should_ReturnStatusCode500()
 {
     var client = new WebDavClient().SetWebDavDispatcher(Dispatcher.MockFaulted());
     var response = await client.Mkcol("http://example.com/new");
     Assert.Equal(500, response.StatusCode);
 }