//Gets the hash list from cloud public List <string> GetHashList() { WebDavClient client = GetWebClient(); //Requests the hash list file from the cloud Task <WebDavStreamResponse> t = client.GetRawFile(_cloudConfig.pathToDir + "Hashlist.txt"); t.Wait(); WebDavStreamResponse result = t.Result; if (result.IsSuccessful) { using (StreamReader reader = new StreamReader(result.Stream)) { //Serializes the response string to a list string text = reader.ReadToEnd(); return(new List <string>(text.Split("\n")).Where(s => !String.IsNullOrEmpty(s)).ToList());; } } else { // Error handling return(null); } }
//Gets the database file from cloud public Byte[] GetCloudVersion() { WebDavClient client = GetWebClient(); //Requests the database file from the cloud Task <WebDavStreamResponse> t = client.GetRawFile(_cloudConfig.pathToDir + "sqlite.db"); t.Wait(); WebDavStreamResponse result = t.Result; if (result.IsSuccessful) { using (var memoryStream = new MemoryStream()) { //Serializes the response stream to byte array result.Stream.CopyTo(memoryStream); return(memoryStream.ToArray()); } } else { // Error handling return(null); } }
//Gets the agent context from cloud public string GetEncryptedAgentOptions() { WebDavClient client = GetWebClient(); //Requests the agent context from the cloud Task <WebDavStreamResponse> t = client.GetRawFile(_cloudConfig.pathToDir + "AgentOptions.json"); t.Wait(); WebDavStreamResponse result = t.Result; if (result.IsSuccessful) { using (StreamReader reader = new StreamReader(result.Stream)) { //Serializes the response stream to string string text = reader.ReadToEnd(); return(text); } } else { // Error handling return(null); } }
public async Task <string> GetFileFromUri(string uri, CancellationToken cancellationToken) { using var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual, SslProtocols = SslProtocols.Tls12 }; try { var certificate = CertificateHelper.GetCertificate(_storeName, _storeLocation, _thumbprint); handler.ClientCertificates.Add(certificate); } catch (Exception ex) { _logger.LogError(ex, $"Fant ikke sertifikat med thumbprint {_thumbprint} StoreName: {_options.Value.StoreName} StoreLocation: {_options.Value.StoreLocation}"); return(null); } using var httpClient = new HttpClient(handler) { BaseAddress = new Uri(_baseAddress), }; using var client = new WebDavClient(httpClient); var getFileParameters = new GetFileParameters { CancellationToken = cancellationToken }; var response = await client.GetRawFile(uri, getFileParameters); var reader = new StreamReader(response.Stream); var fil = await reader.ReadToEndAsync(); return(fil); }
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)); } }
public override async Task SyncFiles() { var result = await _WebDevClient.GetRawFile("KeqingNiuza/BackupFileList.json"); var dirInfo = new DirectoryInfo(".\\UserData"); var localFiles = dirInfo.GetFiles().ToList().ConvertAll(x => new BackupFileinfo(x)); if (result.StatusCode == 404) { result.Dispose(); foreach (var item in localFiles) { await UploadFile(item); } await PutBackupFileList(); return; } StreamReader streamReader = new StreamReader(result.Stream); var json = streamReader.ReadToEnd(); streamReader.Dispose(); result.Dispose(); var remoteFiles = JsonSerializer.Deserialize <List <BackupFileinfo> >(json, JsonOptions); var uploadFiles = localFiles.Where(x => remoteFiles.Any(y => x.Name == y.Name && x.LastUpdateTime > y.LastUpdateTime) || !remoteFiles.Any(y => x.Name == y.Name)).Select(x => x); var downloadFiles = remoteFiles.Where(x => localFiles.Any(y => x.Name == y.Name && x.LastUpdateTime > y.LastUpdateTime) || !localFiles.Any(y => x.Name == y.Name)).Select(x => x); foreach (var item in downloadFiles) { await DownloasFile(item); } foreach (var item in uploadFiles) { await UploadFile(item); } await PutBackupFileList(); LastSyncTime = DateTime.Now; SaveEncyptedAccount(); }
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"); } }
public async Task <ResourceLoadStatus> GetStreamAsync(ResourceItem resourceItem, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(ResourceLoadStatus.OperationCanceled); } if (resourceItem.IsCollection) { return(ResourceLoadStatus.IsCollection); } if (resourceItem.Stream != null && resourceItem.Stream.CanRead) { return(ResourceLoadStatus.StreamExisting); } try { var webDavStreamResponse = await _client.GetRawFile(resourceItem.FullPath).WithCancellation(cancellationToken); if (webDavStreamResponse.IsSuccessful) { resourceItem.Stream = webDavStreamResponse.Stream; resourceItem.MediaDetails = TrackInfoHelper.GetMediaDetails(resourceItem.Stream, new FileInfo(resourceItem.DisplayName).Extension.ToLowerInvariant()); return(ResourceLoadStatus.Ok); } resourceItem.Stream = null; return(ResourceLoadStatus.StreamFailedToLoad); } catch (OperationCanceledException) { return(ResourceLoadStatus.OperationCanceled); } }
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(); }
/// <summary> /// Загрузить файл с удаленого сервера /// </summary> /// <param name="LocalFile">Полный путь к локальному файлу</param> /// <param name="RemoteFile">Полный путь к удаленому файлу</param> /// <param name="EncryptionAES">Использовать шифрование AES 256</param> /// <param name="PasswdAES">Пароль для шифрования файлов</param> /// <param name="FileSize">Размер файла</param> public bool DownloadFile(string LocalFile, string RemoteFile, bool EncryptionAES, string PasswdAES, long FileSize) { // Временный файл string tmpFile = $"{Folders.Temp.SyncBackup}/{md5.text(RemoteFile)}"; // Путь к конечному файлу string targetFile = EncryptionAES ? tmpFile : LocalFile; try { #region Удаляем файлы для перезаписи if (File.Exists(LocalFile)) { File.Delete(LocalFile); } if (File.Exists(tmpFile)) { File.Delete(tmpFile); } #endregion #region Загружаем файл switch (typeSunc) { case TypeSunc.SFTP: { using (FileStream LocalStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write)) { sftp.DownloadFile(RemoteFile, LocalStream); break; } } case TypeSunc.FTP: { ftp.DownloadFile(targetFile, RemoteFile, overwrite: true); break; } case TypeSunc.OneDrive: { var item = oneDrive.GetItem(RemoteFile).Result; if (item == null) { report.DownloadFile(targetFile, RemoteFile, EncryptionAES, FileSize, "OneDrive.GetItem(RemoteFile) == null"); return(false); } oneDrive.DownloadItemAndSaveAs(item, targetFile).Wait(); break; } case TypeSunc.WebDav: { var res = webDav.GetRawFile(RemoteFile).Result; if (!res.IsSuccessful) { report.DownloadFile(targetFile, RemoteFile, EncryptionAES, FileSize, (res.Description, res.StatusCode)); return(false); } using (FileStream LocalStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write)) { CopyStream(res.Stream, LocalStream, FileSize); break; } } } #endregion #region CryptoBox if (EncryptionAES) { using (var сryptoBox = new CryptoBox(PasswdAES, LocalFile, _tmpFile: tmpFile)) { if (!сryptoBox.Decrypt(out string error)) { report.DownloadFile(LocalFile, RemoteFile, EncryptionAES, FileSize, error); return(false); } } } #endregion return(true); } catch (Exception ex) { report.DownloadFile(targetFile, RemoteFile, EncryptionAES, FileSize, ex.ToString()); } return(false); }
/// <summary> /// Загрузить файл с удаленого сервера /// </summary> /// <param name="LocalFile">Полный путь к локальному файлу</param> /// <param name="RemoteFile">Полный путь к удаленому файлу</param> /// <param name="EncryptionAES">Использовать шифрование AES 256</param> /// <param name="PasswdAES">Пароль для шифрования файлов</param> /// <param name="FileSize">Размер файла</param> public bool DownloadFile(string LocalFile, string RemoteFile, bool EncryptionAES, string PasswdAES, long FileSize) { try { // Удаляем локальный файлл если он есть if (File.Exists(LocalFile)) { File.Delete(LocalFile); } // Открываем локальный файл using (var LocalStream = File.OpenWrite(LocalFile)) { #region Получаем поток файла на сервере Stream RemoteStream = null; switch (typeSunc) { case TypeSunc.SFTP: { RemoteStream = sftp.OpenRead(RemoteFile); break; } case TypeSunc.FTP: { RemoteStream = ftp.OpenRead(RemoteFile); break; } case TypeSunc.OneDrive: { var item = oneDrive.GetItem(RemoteFile).Result; if (item == null) { return(false); } report.DownloadFile(LocalFile, RemoteFile, EncryptionAES, FileSize, "OneDrive.GetItem(RemoteFile) == null"); RemoteStream = oneDrive.DownloadItem(item).Result; break; } case TypeSunc.WebDav: { var res = webDav.GetRawFile(RemoteFile).Result; if (!res.IsSuccessful) { report.DownloadFile(LocalFile, RemoteFile, EncryptionAES, FileSize, (res.Description, res.StatusCode)); return(false); } RemoteStream = res.Stream; break; } } #endregion if (EncryptionAES) { var cry = new CryptoBox(PasswdAES); if (!cry.Decrypt(RemoteStream, LocalStream, FileSize, out string error)) { report.DownloadFile(LocalFile, RemoteFile, EncryptionAES, FileSize, error); return(false); } } else { CopyStream(RemoteStream, LocalStream, FileSize); } RemoteStream?.Close(); if (typeSunc == TypeSunc.FTP) { ftp?.GetReply(); } return(true); } } catch (Exception ex) { report.DownloadFile(LocalFile, RemoteFile, EncryptionAES, FileSize, ex.ToString()); } return(false); }