public bool GenerateClient(UpdateServerConfig config)
        {
            bool success;

            try
            {
                // Create client params
                var clientparams = new WebDavClientParams()
                {
                    BaseAddress = new Uri(config.ServerAdress),
                    Credentials = new NetworkCredential(config.Username, config.Password),
                    UseProxy    = false
                };

                // Create client
                client = new WebDavClient(clientparams);

                // Remember config
                Config = config;

                success = true;
            }
            catch (Exception)
            {
                success = false;
                Config  = null;
                client  = null;
            }

            return(success);
        }
Exemplo n.º 2
0
        public async Task <ActionResult> ObterFicheiroNextCloud(string Url)
        {
            var clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri(Url),
                Credentials = new NetworkCredential(ConfigurationManager.AppSetting["NextCloud:User"], ConfigurationManager.AppSetting["NextCloud:Password"])
            };
            var client = new WebDavClient(clientParams);

            using (var response = await client.GetRawFile(Url))
                using (var reader = new StreamReader(response.Stream))
                {
                    var bytes = default(byte[]);
                    using (var memstream = new MemoryStream())
                    {
                        reader.BaseStream.CopyTo(memstream);
                        bytes = memstream.ToArray();
                    }

                    new FileExtensionContentTypeProvider().TryGetContentType(Url.Split('/').Last(), out string contentType);
                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName     = Url.Split('/').Last(),
                        Inline       = false,
                        CreationDate = DateTime.Now,
                    };
                    Response.Headers.Add("Content-Disposition", cd.ToString());

                    return(File(bytes, contentType));
                }
        }
Exemplo n.º 3
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
                }
            }
        }
Exemplo n.º 4
0
        public bool Connect()
        {
            bool result = false;

            if (!IsConnected)
            {
                if (!string.IsNullOrEmpty(settings.WebDavUri))
                {
                    // Set web proxy
                    if (!string.IsNullOrEmpty(settings.ProxyUsr) || !string.IsNullOrEmpty(settings.ProxyPwd))
                    {
                        WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(settings.ProxyUsr, settings.ProxyPwd);
                    }

                    // Create client params
                    var clientparams = new WebDavClientParams()
                    {
                        BaseAddress = new Uri(settings.WebDavUri),
                        Credentials = new NetworkCredential(settings.WebDavUsr.Trim(), settings.WebDavPwd),
                        UseProxy    = false
                    };

                    // Create client
                    client = new WebDavClient(clientparams);

                    result      = true;
                    IsConnected = true;
                }
            }

            return(result);
        }
        private WebDavClient createClient()
        {
            WebDavClientParams parameter = new WebDavClientParams();

            parameter.BaseAddress = new Uri(this._repo.settings.webDavServerUrl);
            parameter.Credentials = new NetworkCredential(this._repo.settings.webDavUsername, this._repo.settings.webDavPassword);
            return(new WebDavClient(parameter));
        }
Exemplo n.º 6
0
        internal WebDavClientParams ConnectParams(LinkDto linkDto)
        {
            var clientParams = new WebDavClientParams {
                BaseAddress = new Uri(linkDto.Address),
                Credentials = new NetworkCredential(linkDto.User, linkDto.Pass)
            };

            return(clientParams);
        }
        public NextCloudClient(NextCloudConfig nextCloudConfig, ILogger <NextCloudClient> logger)
        {
            _webDavClientParams = new WebDavClientParams
            {
                BaseAddress = new Uri($"http://{nextCloudConfig.Host}:{nextCloudConfig.Port}/remote.php/dav/files/{nextCloudConfig.UserName}/"),
                Credentials = new NetworkCredential(nextCloudConfig.UserName, nextCloudConfig.Password)
            };

            _logger = logger;
        }
Exemplo n.º 8
0
        //Initializes the web client
        private WebDavClient GetWebClient()
        {
            var clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri(_cloudConfig.uri),
                Credentials = new NetworkCredential(_cloudConfig.username, _cloudConfig.password)
            };

            return(new WebDavClient(clientParams));
        }
Exemplo n.º 9
0
        private void LoginButton_Clicked_1(object sender, EventArgs e)
        {
            var clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri(setPars.webDavAdress),
                Credentials = new NetworkCredential(setPars.webLogin, setPars.webPass)
            };

            _client       = new WebDavClient(clientParams);
            documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            TryConnect();
        }
Exemplo n.º 10
0
        public Form1()
        {
            InitializeComponent();

            var clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri(baseUrl),
                Credentials = new NetworkCredential("userid", "userpw")
                              //Timeout = new TimeSpan(3000)
            };

            client = new WebDavClient(clientParams);
        }
Exemplo n.º 11
0
        public async Task <string> Upload()
        {
            if (string.IsNullOrEmpty(_options.UploadBaseUrl))
            {
                return("skipped upload\r\n");
            }

            var clientParams = new WebDavClientParams {
                BaseAddress = new Uri(_options.UploadBaseUrl)
            };

            using (var webDavClient = new WebDavClient(clientParams))
            {
                var songResponse = await webDavClient.Propfind(_options.UploadSongUrl).ConfigureAwait(false);

                if (!songResponse.IsSuccessful)
                {
                    return("upload propfind failed\r\n");
                }

                var existingSongs   = songResponse.Resources.Select(x => new { x.Uri, FileName = Path.GetFileName(Uri.UnescapeDataString(x.Uri)).Normalize() }).Where(x => !string.IsNullOrEmpty(x.FileName)).ToList();
                var downloadPath    = Path.Combine(_options.DownloadBasePath, _options.DownloadSongPath);
                var downloadedSongs = Directory.GetFiles(downloadPath);

                var output = new StringBuilder();
                foreach (var downloadedSong in downloadedSongs)
                {
                    var songFileName = Path.GetFileName(downloadedSong);
                    if (existingSongs.Any(x => x.FileName == songFileName))
                    {
                        continue;
                    }

                    // upload
                    _logger.LogInformation("uploading {0}", songFileName);
                    output.AppendLine($"uploading {songFileName}");
                    using (var fileStream = System.IO.File.OpenRead(downloadedSong))
                    {
                        await webDavClient.PutFile($"{_options.UploadSongUrl}/{Uri.EscapeDataString(songFileName)}", fileStream).ConfigureAwait(false);
                    }
                }

                if (output.Length == 0)
                {
                    output.AppendLine("uploaded none");
                }

                return(output.ToString());
            }
        }
Exemplo n.º 12
0
        public WebDavSyncClient(ILogger logger, Configuration config)
        {
            _logger      = logger;
            _config      = config;
            _lockManager = new WebDavLockManager(logger);

            WebDavClientParams clientParams = new WebDavClientParams()
            {
                //Credentials = config.Remote.Credentials,
                Credentials = config.Remote.Credentials,
                BaseAddress = new Uri(_config.Remote.RemoteServerPath)
            };

            _webDavClient = new WebDavClient(clientParams);
        }
Exemplo n.º 13
0
        static async void Test()
        {
            var clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri("http://192.168.10.242/owncloud/remote.php/webdav/"),
                Credentials = new System.Net.NetworkCredential("admin", "admin")
            };

            using (var webDavClient = new WebDavClient(clientParams))
            {
                var result = await webDavClient.Propfind("/KV/mydir");

                Console.WriteLine("result :" + result);
            }
        }
Exemplo n.º 14
0
        private WebDavClient CreateClient(TweakDatabaseLoginTypes t)
        {
            if (!dicClients.ContainsKey(t))
            {
                var login   = Preferences.Logins[t];
                var @params = new WebDavClientParams()
                {
                    BaseAddress = new Uri(login.Link),
                    Credentials = new NetworkCredential(login.Username, login.Password),
                    UseProxy    = false
                };
                dicClients.Add(t, new WebDavClient(@params));
            }

            return(dicClients[t]);
        }
Exemplo n.º 15
0
        static async Task Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Needed arguments:\r\n1. Webdav base address\r\n2. User\r\n3. Password\r\n4. Localshare");
                return;
            }

            var baseAddress = args[0].ToString();
            var user        = args[1].ToString();
            var pass        = args[2].ToString();
            var localShare  = args[3].ToString();

            Console.WriteLine($"1. Webdav base address: {baseAddress}\r\n2. User: {user}\r\n3. Password: ****\r\n4. Localshare: {localShare}");

            var clientParams = new WebDavClientParams
            {
                BaseAddress = new Uri(baseAddress),
                Credentials = new NetworkCredential(user, pass)
            };

            _client = new WebDavClient(clientParams);

            var files = Directory.GetFiles(localShare, "*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                //var isUploaded = await CheckIfFileIsUploaded(baseAddress, file.Replace(localShare, string.Empty));

                var size = new System.IO.FileInfo(file).Length;
                var isUploadedAndSameSize = await CheckIfFileIsUploadedAndSameSize(baseAddress, file.Replace(localShare, string.Empty), size);

                if (!isUploadedAndSameSize)
                {
                    Console.WriteLine($"MISSING: {file}");
                }
                else
                {
                    Console.WriteLine($"OKAY: {file}");
                }
            }
        }
Exemplo n.º 16
0
        public static Task <WebDavClient> LoginAsync(string account, string code, Uri baseAddress, string settingsPassPhrase)
        {
            if (string.IsNullOrEmpty(account))
            {
                throw new ArgumentNullException(nameof(account));
            }
            if (baseAddress == null)
            {
                throw new ArgumentNullException(nameof(baseAddress));
            }

            var credential = LoadCredential(account, settingsPassPhrase);

            if (credential == null)
            {
                if (string.IsNullOrEmpty(code))
                {
                    code = GetAuthCode(account);
                }

                var parts = code?.Split(new[] { ',' }, 2) ?? Array.Empty <string>();
                if (parts.Length != 2)
                {
                    throw new AuthenticationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.ProvideAuthenticationData, account));
                }

                credential = new NetworkCredential(parts[0], parts[1]);
            }

            SaveCredential(account, credential, settingsPassPhrase);

            var clientParams = new WebDavClientParams()
            {
                BaseAddress           = baseAddress,
                Credentials           = credential,
                UseDefaultCredentials = false
            };

            return(Task.FromResult(new WebDavClient(clientParams)));
        }
Exemplo n.º 17
0
        public OwnCloudClient(string ownCloudHost, string user, string password)
        {
            this.client = new HttpClient
            {
                BaseAddress = new Uri($"{ownCloudHost?.TrimEnd('/')}/ocs/v1.php/apps/files_sharing/api/v1/"),
            };

            var byteArray = Encoding.ASCII.GetBytes($"{user}:{password}");

            this.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic",
                Convert.ToBase64String(byteArray));

            var webDavParams = new WebDavClientParams
            {
                BaseAddress = new Uri($"{ownCloudHost?.TrimEnd('/')}/remote.php/webdav/"),
            };

            webDavParams.DefaultRequestHeaders.Add("Authorization", new AuthenticationHeaderValue(
                                                       "Basic",
                                                       Convert.ToBase64String(byteArray)).ToString());

            this.webDav = new WebDavClient(webDavParams);
        }
Exemplo n.º 18
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();
        }