Skip to content

Commit

Permalink
Add backup and restore
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Sep 7, 2024
1 parent d5f1cc9 commit beddc71
Show file tree
Hide file tree
Showing 17 changed files with 889 additions and 14 deletions.
44 changes: 43 additions & 1 deletion v2rayN/ServiceLib/Common/FileManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,12 @@ public static bool CreateFromDirectory(string sourceDirectoryName, string destin
{
try
{
ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName);
if (File.Exists(destinationArchiveFileName))
{
File.Delete(destinationArchiveFileName);
}

ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, CompressionLevel.SmallestSize, true);
}
catch (Exception ex)
{
Expand All @@ -115,5 +120,42 @@ public static bool CreateFromDirectory(string sourceDirectoryName, string destin
}
return true;
}

public static void CopyDirectory(string sourceDir, string destinationDir, bool recursive, string ignoredName)
{
// Get information about the source directory
var dir = new DirectoryInfo(sourceDir);

// Check if the source directory exists
if (!dir.Exists)
throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}");

// Cache directories before we start copying
DirectoryInfo[] dirs = dir.GetDirectories();

// Create the destination directory
Directory.CreateDirectory(destinationDir);

// Get the files in the source directory and copy to the destination directory
foreach (FileInfo file in dir.GetFiles())
{
if (!Utils.IsNullOrEmpty(ignoredName) && file.Name.Contains(ignoredName))
{
continue;
}
string targetFilePath = Path.Combine(destinationDir, file.Name);
file.CopyTo(targetFilePath);
}

// If recursive and copying subdirectories, recursively call this method
if (recursive)
{
foreach (DirectoryInfo subDir in dirs)
{
string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
CopyDirectory(subDir.FullName, newDestinationDir, true, ignoredName);
}
}
}
}
}
2 changes: 2 additions & 0 deletions v2rayN/ServiceLib/Handler/ConfigHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,8 @@ public static int LoadConfig(ref Config? config)
};
}

config.webDavItem ??= new();

return 0;
}

Expand Down
2 changes: 1 addition & 1 deletion v2rayN/ServiceLib/Handler/NoticeHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public void SendMessage(string? content)
MessageBus.Current.SendMessage(content, Global.CommandSendMsgView);
}

public void SendMessageEx(string? content )
public void SendMessageEx(string? content)
{
if (content.IsNullOrEmpty())
{
Expand Down
163 changes: 163 additions & 0 deletions v2rayN/ServiceLib/Handler/WebDavHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
using System.Net;
using WebDav;

namespace ServiceLib.Handler
{
public sealed class WebDavHandler
{
private static readonly Lazy<WebDavHandler> _instance = new(() => new());
public static WebDavHandler Instance => _instance.Value;

private Config? _config;
private WebDavClient? _client;
private string? _lastDescription;
private string _webDir = "mywebdir";
private string _webFileName = "backup.zip";
private string _logTitle = "WebDav--";

public WebDavHandler()
{
_config = LazyConfig.Instance.Config;
}

private async Task<bool> GetClient()
{
try
{
if (_config.webDavItem.url.IsNullOrEmpty()
|| _config.webDavItem.userName.IsNullOrEmpty()
|| _config.webDavItem.password.IsNullOrEmpty())
{
throw new ArgumentException("webdav parameter error or null");
}
if (_client != null)
{
_client?.Dispose();
_client = null;
}

var clientParams = new WebDavClientParams
{
BaseAddress = new Uri(_config.webDavItem.url),
Credentials = new NetworkCredential(_config.webDavItem.userName, _config.webDavItem.password)
};
_client = new WebDavClient(clientParams);
}
catch (Exception ex)
{
SaveLog(ex);
return false;
}
return await Task.FromResult(true);
}

private async Task<bool> CheckProp()
{
if (_client is null) return false;
try
{
var result = await _client.Propfind(_webDir);
if (result.IsSuccessful)
{
return true;
}
var result2 = await _client.Mkcol(_webDir); // create a directory
if (result2.IsSuccessful)
{
return true;
}
SaveLog(result2.Description);
}
catch (Exception ex)
{
SaveLog(ex);
}
return false;
}

private void SaveLog(string desc)
{
_lastDescription = desc;
Logging.SaveLog(_logTitle + desc);
}

private void SaveLog(Exception ex)
{
_lastDescription = ex.Message;
Logging.SaveLog(_logTitle, ex);
}

public async Task<bool> CheckConnection()
{
if (await GetClient() == false)
{
return false;
}
if (await CheckProp() == false)
{
return false;
}

return true;
}

public async Task<bool> PutFile(string fileName)
{
if (await GetClient() == false)
{
return false;
}
if (await CheckProp() == false)
{
return false;
}

try
{
using var fs = File.OpenRead(fileName);
var result = await _client.PutFile($"{_webDir}/{_webFileName}", fs); // upload a resource
if (result.IsSuccessful)
{
return true;
}

SaveLog(result.Description);
}
catch (Exception ex)
{
SaveLog(ex);
}
return false;
}

public async Task<bool> GetRawFile(string fileName)
{
if (await GetClient() == false)
{
return false;
}
if (await CheckProp() == false)
{
return false;
}
try
{
var response = await _client.GetRawFile($"{_webDir}/{_webFileName}");
if (!response.IsSuccessful)
{
SaveLog(response.Description);
}
using var outputFileStream = new FileStream(fileName, FileMode.Create);
response.Stream.CopyTo(outputFileStream);
return true;
}
catch (Exception ex)
{
SaveLog(ex);
}
return false;
}

public string GetLastError() => _lastDescription ?? string.Empty;
}
}
1 change: 1 addition & 0 deletions v2rayN/ServiceLib/Models/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public bool IsRunningCore(ECoreType type)
public HysteriaItem hysteriaItem { get; set; }
public ClashUIItem clashUIItem { get; set; }
public SystemProxyItem systemProxyItem { get; set; }
public WebDavItem webDavItem { get; set; }
public List<InItem> inbound { get; set; }
public List<KeyEventItem> globalHotkeys { get; set; }
public List<CoreTypeItem> coreTypeItem { get; set; }
Expand Down
8 changes: 8 additions & 0 deletions v2rayN/ServiceLib/Models/ConfigItems.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,4 +248,12 @@ public class SystemProxyItem
public bool notProxyLocalAddress { get; set; } = true;
public string systemProxyAdvancedProtocol { get; set; }
}

[Serializable]
public class WebDavItem
{
public string? url { get; set; }
public string? userName { get; set; }
public string? password { get; set; }
}
}
99 changes: 99 additions & 0 deletions v2rayN/ServiceLib/Resx/ResUI.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit beddc71

Please sign in to comment.