mirror of
https://github.com/2dust/v2rayN.git
synced 2025-07-01 12:32:10 +00:00
Refactor Common
This commit is contained in:
parent
6b99b7eec5
commit
019c69ecff
11 changed files with 49 additions and 75 deletions
|
@ -36,7 +36,7 @@ namespace ServiceLib.Common
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
using var downloader = new Downloader.DownloadService(downloadOpt);
|
await using var downloader = new Downloader.DownloadService(downloadOpt);
|
||||||
downloader.DownloadFileCompleted += (sender, value) =>
|
downloader.DownloadFileCompleted += (sender, value) =>
|
||||||
{
|
{
|
||||||
if (value.Error != null)
|
if (value.Error != null)
|
||||||
|
@ -46,12 +46,12 @@ namespace ServiceLib.Common
|
||||||
};
|
};
|
||||||
|
|
||||||
using var cts = new CancellationTokenSource();
|
using var cts = new CancellationTokenSource();
|
||||||
using var stream = await downloader.DownloadFileTaskAsync(address: url, cts.Token).WaitAsync(TimeSpan.FromSeconds(timeout), cts.Token);
|
await using var stream = await downloader.DownloadFileTaskAsync(address: url, cts.Token).WaitAsync(TimeSpan.FromSeconds(timeout), cts.Token);
|
||||||
using StreamReader reader = new(stream);
|
using StreamReader reader = new(stream);
|
||||||
|
|
||||||
downloadOpt = null;
|
downloadOpt = null;
|
||||||
|
|
||||||
return reader.ReadToEnd();
|
return await reader.ReadToEndAsync(cts.Token);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress<string> progress, int timeout)
|
public async Task DownloadDataAsync4Speed(IWebProxy webProxy, string url, IProgress<string> progress, int timeout)
|
||||||
|
@ -72,11 +72,11 @@ namespace ServiceLib.Common
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
DateTime totalDatetime = DateTime.Now;
|
var totalDatetime = DateTime.Now;
|
||||||
int totalSecond = 0;
|
var totalSecond = 0;
|
||||||
var hasValue = false;
|
var hasValue = false;
|
||||||
double maxSpeed = 0;
|
double maxSpeed = 0;
|
||||||
using var downloader = new Downloader.DownloadService(downloadOpt);
|
await using var downloader = new Downloader.DownloadService(downloadOpt);
|
||||||
//downloader.DownloadStarted += (sender, value) =>
|
//downloader.DownloadStarted += (sender, value) =>
|
||||||
//{
|
//{
|
||||||
// if (progress != null)
|
// if (progress != null)
|
||||||
|
@ -86,7 +86,7 @@ namespace ServiceLib.Common
|
||||||
//};
|
//};
|
||||||
downloader.DownloadProgressChanged += (sender, value) =>
|
downloader.DownloadProgressChanged += (sender, value) =>
|
||||||
{
|
{
|
||||||
TimeSpan ts = (DateTime.Now - totalDatetime);
|
var ts = (DateTime.Now - totalDatetime);
|
||||||
if (progress != null && ts.Seconds > totalSecond)
|
if (progress != null && ts.Seconds > totalSecond)
|
||||||
{
|
{
|
||||||
hasValue = true;
|
hasValue = true;
|
||||||
|
@ -112,7 +112,7 @@ namespace ServiceLib.Common
|
||||||
//progress.Report("......");
|
//progress.Report("......");
|
||||||
using var cts = new CancellationTokenSource();
|
using var cts = new CancellationTokenSource();
|
||||||
cts.CancelAfter(timeout * 1000);
|
cts.CancelAfter(timeout * 1000);
|
||||||
using var stream = await downloader.DownloadFileTaskAsync(address: url, cts.Token);
|
await using var stream = await downloader.DownloadFileTaskAsync(address: url, cts.Token);
|
||||||
|
|
||||||
downloadOpt = null;
|
downloadOpt = null;
|
||||||
}
|
}
|
||||||
|
@ -145,7 +145,7 @@ namespace ServiceLib.Common
|
||||||
|
|
||||||
var progressPercentage = 0;
|
var progressPercentage = 0;
|
||||||
var hasValue = false;
|
var hasValue = false;
|
||||||
using var downloader = new Downloader.DownloadService(downloadOpt);
|
await using var downloader = new Downloader.DownloadService(downloadOpt);
|
||||||
downloader.DownloadStarted += (sender, value) =>
|
downloader.DownloadStarted += (sender, value) =>
|
||||||
{
|
{
|
||||||
progress?.Report(0);
|
progress?.Report(0);
|
||||||
|
|
|
@ -23,7 +23,7 @@ namespace ServiceLib.Common
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using FileStream fs = File.Create(fileName);
|
using var fs = File.Create(fileName);
|
||||||
using GZipStream input = new(new MemoryStream(content), CompressionMode.Decompress, false);
|
using GZipStream input = new(new MemoryStream(content), CompressionMode.Decompress, false);
|
||||||
input.CopyTo(fs);
|
input.CopyTo(fs);
|
||||||
}
|
}
|
||||||
|
@ -38,8 +38,8 @@ namespace ServiceLib.Common
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
FileInfo fileInfo = new(fileName);
|
FileInfo fileInfo = new(fileName);
|
||||||
using FileStream originalFileStream = fileInfo.OpenRead();
|
using var originalFileStream = fileInfo.OpenRead();
|
||||||
using FileStream decompressedFileStream = File.Create(toName != null ? Path.Combine(toPath, toName) : toPath);
|
using var decompressedFileStream = File.Create(toName != null ? Path.Combine(toPath, toName) : toPath);
|
||||||
using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);
|
using GZipStream decompressionStream = new(originalFileStream, CompressionMode.Decompress);
|
||||||
decompressionStream.CopyTo(decompressedFileStream);
|
decompressionStream.CopyTo(decompressedFileStream);
|
||||||
}
|
}
|
||||||
|
@ -54,7 +54,7 @@ namespace ServiceLib.Common
|
||||||
return NonExclusiveReadAllText(path, Encoding.Default);
|
return NonExclusiveReadAllText(path, Encoding.Default);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string NonExclusiveReadAllText(string path, Encoding encoding)
|
private static string NonExclusiveReadAllText(string path, Encoding encoding)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
@ -73,8 +73,8 @@ namespace ServiceLib.Common
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using ZipArchive archive = ZipFile.OpenRead(fileName);
|
using var archive = ZipFile.OpenRead(fileName);
|
||||||
foreach (ZipArchiveEntry entry in archive.Entries)
|
foreach (var entry in archive.Entries)
|
||||||
{
|
{
|
||||||
if (entry.Length == 0)
|
if (entry.Length == 0)
|
||||||
{
|
{
|
||||||
|
@ -110,7 +110,7 @@ namespace ServiceLib.Common
|
||||||
}
|
}
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using ZipArchive archive = ZipFile.OpenRead(fileName);
|
using var archive = ZipFile.OpenRead(fileName);
|
||||||
return archive.Entries.Select(entry => entry.FullName).ToList();
|
return archive.Entries.Select(entry => entry.FullName).ToList();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
@ -149,13 +149,13 @@ namespace ServiceLib.Common
|
||||||
throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}");
|
throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}");
|
||||||
|
|
||||||
// Cache directories before we start copying
|
// Cache directories before we start copying
|
||||||
DirectoryInfo[] dirs = dir.GetDirectories();
|
var dirs = dir.GetDirectories();
|
||||||
|
|
||||||
// Create the destination directory
|
// Create the destination directory
|
||||||
Directory.CreateDirectory(destinationDir);
|
Directory.CreateDirectory(destinationDir);
|
||||||
|
|
||||||
// Get the files in the source directory and copy to the destination directory
|
// Get the files in the source directory and copy to the destination directory
|
||||||
foreach (FileInfo file in dir.GetFiles())
|
foreach (var file in dir.GetFiles())
|
||||||
{
|
{
|
||||||
if (Utils.IsNotEmpty(ignoredName) && file.Name.Contains(ignoredName))
|
if (Utils.IsNotEmpty(ignoredName) && file.Name.Contains(ignoredName))
|
||||||
{
|
{
|
||||||
|
@ -165,16 +165,16 @@ namespace ServiceLib.Common
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
string targetFilePath = Path.Combine(destinationDir, file.Name);
|
var targetFilePath = Path.Combine(destinationDir, file.Name);
|
||||||
file.CopyTo(targetFilePath);
|
file.CopyTo(targetFilePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If recursive and copying subdirectories, recursively call this method
|
// If recursive and copying subdirectories, recursively call this method
|
||||||
if (recursive)
|
if (recursive)
|
||||||
{
|
{
|
||||||
foreach (DirectoryInfo subDir in dirs)
|
foreach (var subDir in dirs)
|
||||||
{
|
{
|
||||||
string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
|
var newDestinationDir = Path.Combine(destinationDir, subDir.Name);
|
||||||
CopyDirectory(subDir.FullName, newDestinationDir, true, ignoredName);
|
CopyDirectory(subDir.FullName, newDestinationDir, true, ignoredName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,7 +27,7 @@ namespace ServiceLib.Common
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
HttpResponseMessage response = await httpClient.GetAsync(url);
|
var response = await httpClient.GetAsync(url);
|
||||||
return await response.Content.ReadAsStringAsync();
|
return await response.Content.ReadAsStringAsync();
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
|
@ -84,8 +84,8 @@ namespace ServiceLib.Common
|
||||||
var total = response.Content.Headers.ContentLength ?? -1L;
|
var total = response.Content.Headers.ContentLength ?? -1L;
|
||||||
var canReportProgress = total != -1 && progress != null;
|
var canReportProgress = total != -1 && progress != null;
|
||||||
|
|
||||||
using var stream = await response.Content.ReadAsStreamAsync(token);
|
await using var stream = await response.Content.ReadAsStreamAsync(token);
|
||||||
using var file = File.Create(fileName);
|
await using var file = File.Create(fileName);
|
||||||
var totalRead = 0L;
|
var totalRead = 0L;
|
||||||
var buffer = new byte[1024 * 1024];
|
var buffer = new byte[1024 * 1024];
|
||||||
var progressPercentage = 0;
|
var progressPercentage = 0;
|
||||||
|
@ -98,7 +98,7 @@ namespace ServiceLib.Common
|
||||||
totalRead += read;
|
totalRead += read;
|
||||||
|
|
||||||
if (read == 0) break;
|
if (read == 0) break;
|
||||||
file.Write(buffer, 0, read);
|
await file.WriteAsync(buffer, 0, read, token);
|
||||||
|
|
||||||
if (canReportProgress)
|
if (canReportProgress)
|
||||||
{
|
{
|
||||||
|
@ -133,13 +133,13 @@ namespace ServiceLib.Common
|
||||||
//var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
|
//var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
|
||||||
//var canReportProgress = total != -1 && progress != null;
|
//var canReportProgress = total != -1 && progress != null;
|
||||||
|
|
||||||
using var stream = await response.Content.ReadAsStreamAsync(token);
|
await using var stream = await response.Content.ReadAsStreamAsync(token);
|
||||||
var totalRead = 0L;
|
var totalRead = 0L;
|
||||||
var buffer = new byte[1024 * 64];
|
var buffer = new byte[1024 * 64];
|
||||||
var isMoreToRead = true;
|
var isMoreToRead = true;
|
||||||
string progressSpeed = string.Empty;
|
var progressSpeed = string.Empty;
|
||||||
DateTime totalDatetime = DateTime.Now;
|
var totalDatetime = DateTime.Now;
|
||||||
int totalSecond = 0;
|
var totalSecond = 0;
|
||||||
|
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
|
@ -168,7 +168,7 @@ namespace ServiceLib.Common
|
||||||
|
|
||||||
totalRead += read;
|
totalRead += read;
|
||||||
|
|
||||||
TimeSpan ts = (DateTime.Now - totalDatetime);
|
var ts = (DateTime.Now - totalDatetime);
|
||||||
if (progress != null && ts.Seconds > totalSecond)
|
if (progress != null && ts.Seconds > totalSecond)
|
||||||
{
|
{
|
||||||
totalSecond = ts.Seconds;
|
totalSecond = ts.Seconds;
|
||||||
|
|
|
@ -8,7 +8,7 @@ namespace ServiceLib.Common
|
||||||
* http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net
|
* http://stackoverflow.com/questions/6266820/working-example-of-createjobobject-setinformationjobobject-pinvoke-in-net
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public class Job : IDisposable
|
public sealed class Job : IDisposable
|
||||||
{
|
{
|
||||||
private IntPtr handle = IntPtr.Zero;
|
private IntPtr handle = IntPtr.Zero;
|
||||||
|
|
||||||
|
@ -73,7 +73,7 @@ namespace ServiceLib.Common
|
||||||
GC.SuppressFinalize(this);
|
GC.SuppressFinalize(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected virtual void Dispose(bool disposing)
|
private void Dispose(bool disposing)
|
||||||
{
|
{
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
disposed = true;
|
disposed = true;
|
||||||
|
|
|
@ -69,7 +69,7 @@ namespace ServiceLib.Common
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Serialize(object? obj, bool indented = true)
|
public static string Serialize(object? obj, bool indented = true)
|
||||||
{
|
{
|
||||||
string result = string.Empty;
|
var result = string.Empty;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
|
@ -112,7 +112,7 @@ namespace ServiceLib.Common
|
||||||
}
|
}
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using FileStream file = File.Create(filePath);
|
using var file = File.Create(filePath);
|
||||||
|
|
||||||
var options = new JsonSerializerOptions
|
var options = new JsonSerializerOptions
|
||||||
{
|
{
|
||||||
|
|
|
@ -7,7 +7,7 @@ namespace ServiceLib.Common
|
||||||
public static byte[]? GenQRCode(string? url)
|
public static byte[]? GenQRCode(string? url)
|
||||||
{
|
{
|
||||||
using QRCodeGenerator qrGenerator = new();
|
using QRCodeGenerator qrGenerator = new();
|
||||||
using QRCodeData qrCodeData = qrGenerator.CreateQrCode(url ?? string.Empty, QRCodeGenerator.ECCLevel.Q);
|
using var qrCodeData = qrGenerator.CreateQrCode(url ?? string.Empty, QRCodeGenerator.ECCLevel.Q);
|
||||||
using PngByteQRCode qrCode = new(qrCodeData);
|
using PngByteQRCode qrCode = new(qrCodeData);
|
||||||
return qrCode.GetGraphic(20);
|
return qrCode.GetGraphic(20);
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,7 @@ namespace ServiceLib.Common
|
||||||
|
|
||||||
private static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc)
|
private static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc)
|
||||||
{
|
{
|
||||||
string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";
|
var methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";
|
||||||
|
|
||||||
var memberProp = typeof(T).GetProperty(propertyName);
|
var memberProp = typeof(T).GetProperty(propertyName);
|
||||||
|
|
||||||
|
|
|
@ -28,14 +28,14 @@
|
||||||
}
|
}
|
||||||
this.version = version.RemovePrefix('v');
|
this.version = version.RemovePrefix('v');
|
||||||
|
|
||||||
string[] parts = this.version.Split('.');
|
var parts = this.version.Split('.');
|
||||||
if (parts.Length == 2)
|
if (parts.Length == 2)
|
||||||
{
|
{
|
||||||
this.major = int.Parse(parts[0]);
|
this.major = int.Parse(parts[0]);
|
||||||
this.minor = int.Parse(parts[1]);
|
this.minor = int.Parse(parts[1]);
|
||||||
this.patch = 0;
|
this.patch = 0;
|
||||||
}
|
}
|
||||||
else if (parts.Length == 3 || parts.Length == 4)
|
else if (parts.Length is 3 or 4)
|
||||||
{
|
{
|
||||||
this.major = int.Parse(parts[0]);
|
this.major = int.Parse(parts[0]);
|
||||||
this.minor = int.Parse(parts[1]);
|
this.minor = int.Parse(parts[1]);
|
||||||
|
|
|
@ -11,7 +11,7 @@ namespace ServiceLib.Common
|
||||||
private SQLiteConnection _db;
|
private SQLiteConnection _db;
|
||||||
private SQLiteAsyncConnection _dbAsync;
|
private SQLiteAsyncConnection _dbAsync;
|
||||||
private static readonly object objLock = new();
|
private static readonly object objLock = new();
|
||||||
public readonly string _configDB = "guiNDB.db";
|
private readonly string _configDB = "guiNDB.db";
|
||||||
|
|
||||||
public SQLiteHelper()
|
public SQLiteHelper()
|
||||||
{
|
{
|
||||||
|
|
|
@ -25,21 +25,14 @@ namespace ServiceLib.Common
|
||||||
return chars.Contains(s[0]);
|
return chars.Contains(s[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool IsWhiteSpace(this string value)
|
private static bool IsWhiteSpace(this string value)
|
||||||
{
|
{
|
||||||
foreach (char c in value)
|
return value.All(char.IsWhiteSpace);
|
||||||
{
|
|
||||||
if (char.IsWhiteSpace(c)) continue;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IEnumerable<string> NonWhiteSpaceLines(this TextReader reader)
|
public static IEnumerable<string> NonWhiteSpaceLines(this TextReader reader)
|
||||||
{
|
{
|
||||||
string? line;
|
while (reader.ReadLine() is { } line)
|
||||||
while ((line = reader.ReadLine()) != null)
|
|
||||||
{
|
{
|
||||||
if (line.IsWhiteSpace()) continue;
|
if (line.IsWhiteSpace()) continue;
|
||||||
yield return line;
|
yield return line;
|
||||||
|
@ -53,26 +46,12 @@ namespace ServiceLib.Common
|
||||||
|
|
||||||
public static string RemovePrefix(this string value, char prefix)
|
public static string RemovePrefix(this string value, char prefix)
|
||||||
{
|
{
|
||||||
if (value.StartsWith(prefix))
|
return value.StartsWith(prefix) ? value[1..] : value;
|
||||||
{
|
|
||||||
return value.Substring(1);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string RemovePrefix(this string value, string prefix)
|
public static string RemovePrefix(this string value, string prefix)
|
||||||
{
|
{
|
||||||
if (value.StartsWith(prefix))
|
return value.StartsWith(prefix) ? value[prefix.Length..] : value;
|
||||||
{
|
|
||||||
return value.Substring(prefix.Length);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string UpperFirstChar(this string value)
|
public static string UpperFirstChar(this string value)
|
||||||
|
@ -82,17 +61,12 @@ namespace ServiceLib.Common
|
||||||
return string.Empty;
|
return string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
return char.ToUpper(value[0]) + value.Substring(1);
|
return char.ToUpper(value[0]) + value[1..];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string AppendQuotes(this string value)
|
public static string AppendQuotes(this string value)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(value))
|
return string.IsNullOrEmpty(value) ? string.Empty : $"\"{value}\"";
|
||||||
{
|
|
||||||
return string.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $"\"{value}\"";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -21,7 +21,7 @@ namespace ServiceLib.Common
|
||||||
.Build();
|
.Build();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
T obj = deserializer.Deserialize<T>(str);
|
var obj = deserializer.Deserialize<T>(str);
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
@ -36,9 +36,9 @@ namespace ServiceLib.Common
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string ToYaml(Object? obj)
|
public static string ToYaml(object? obj)
|
||||||
{
|
{
|
||||||
string result = string.Empty;
|
var result = string.Empty;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
{
|
{
|
||||||
return result;
|
return result;
|
||||||
|
|
Loading…
Reference in a new issue