Skip to content

Commit

Permalink
Code clean
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Jan 30, 2025
1 parent 253219d commit 4526400
Show file tree
Hide file tree
Showing 103 changed files with 640 additions and 499 deletions.
7 changes: 4 additions & 3 deletions v2rayN/AmazTool/UpgradeApp.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Diagnostics;
using System.Diagnostics;
using System.IO.Compression;
using System.Text;

Expand Down Expand Up @@ -59,7 +59,8 @@ public static void Upgrade(string fileName)
Console.WriteLine(entry.FullName);

var lst = entry.FullName.Split(splitKey);
if (lst.Length == 1) continue;
if (lst.Length == 1)
continue;
var fullName = string.Join(splitKey, lst[1..lst.Length]);

if (string.Equals(Utils.GetExePath(), Utils.GetPath(fullName), StringComparison.OrdinalIgnoreCase))
Expand Down Expand Up @@ -101,4 +102,4 @@ public static void Upgrade(string fileName)
Utils.StartV2RayN();
}
}
}
}
4 changes: 2 additions & 2 deletions v2rayN/ServiceLib/Common/DownloaderHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using Downloader;
using System.Net;
using Downloader;

namespace ServiceLib.Common
{
Expand Down Expand Up @@ -181,4 +181,4 @@ public async Task DownloadFileAsync(IWebProxy? webProxy, string url, string file
downloadOpt = null;
}
}
}
}
17 changes: 11 additions & 6 deletions v2rayN/ServiceLib/Common/HttpClientHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@ public class HttpClientHelper

public async Task<string?> GetAsync(string url)
{
if (Utils.IsNullOrEmpty(url)) return null;
if (Utils.IsNullOrEmpty(url))
return null;
return await httpClient.GetStringAsync(url);
}

public async Task<string?> GetAsync(HttpClient client, string url, CancellationToken token = default)
{
if (Utils.IsNullOrEmpty(url)) return null;
if (Utils.IsNullOrEmpty(url))
return null;
return await client.GetStringAsync(url, token);
}

Expand Down Expand Up @@ -75,11 +77,13 @@ public static async Task DownloadFileAsync(HttpClient client, string url, string
{
ArgumentNullException.ThrowIfNull(url);
ArgumentNullException.ThrowIfNull(fileName);
if (File.Exists(fileName)) File.Delete(fileName);
if (File.Exists(fileName))
File.Delete(fileName);

using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);

if (!response.IsSuccessStatusCode) throw new Exception(response.StatusCode.ToString());
if (!response.IsSuccessStatusCode)
throw new Exception(response.StatusCode.ToString());

var total = response.Content.Headers.ContentLength ?? -1L;
var canReportProgress = total != -1 && progress != null;
Expand All @@ -97,7 +101,8 @@ public static async Task DownloadFileAsync(HttpClient client, string url, string
var read = await stream.ReadAsync(buffer, token);
totalRead += read;

if (read == 0) break;
if (read == 0)
break;
await file.WriteAsync(buffer.AsMemory(0, read), token);

if (canReportProgress)
Expand Down Expand Up @@ -183,4 +188,4 @@ public async Task DownloadDataAsync4Speed(HttpClient client, string url, IProgre
} while (isMoreToRead);
}
}
}
}
7 changes: 4 additions & 3 deletions v2rayN/ServiceLib/Common/Job.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Diagnostics;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ServiceLib.Common
Expand Down Expand Up @@ -75,7 +75,8 @@ public void Dispose()

private void Dispose(bool disposing)
{
if (disposed) return;
if (disposed)
return;
disposed = true;

if (disposing)
Expand Down Expand Up @@ -173,4 +174,4 @@ public enum JobObjectInfoType
}

#endregion Helper classes
}
}
10 changes: 6 additions & 4 deletions v2rayN/ServiceLib/Common/Logging.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using NLog;
using NLog;
using NLog.Config;
using NLog.Targets;

Expand Down Expand Up @@ -27,14 +27,16 @@ public static void LoggingEnabled(bool enable)

public static void SaveLog(string strContent)
{
if (!LogManager.IsLoggingEnabled()) return;
if (!LogManager.IsLoggingEnabled())
return;

LogManager.GetLogger("Log1").Info(strContent);
}

public static void SaveLog(string strTitle, Exception ex)
{
if (!LogManager.IsLoggingEnabled()) return;
if (!LogManager.IsLoggingEnabled())
return;

var logger = LogManager.GetLogger("Log2");
logger.Debug($"{strTitle},{ex.Message}");
Expand All @@ -45,4 +47,4 @@ public static void SaveLog(string strTitle, Exception ex)
}
}
}
}
}
27 changes: 19 additions & 8 deletions v2rayN/ServiceLib/Common/ProcUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ public static void ProcessStart(string? fileName, string arguments = "")
}
try
{
if (fileName.Contains(' ')) fileName = fileName.AppendQuotes();
if (arguments.Contains(' ')) arguments = arguments.AppendQuotes();
if (fileName.Contains(' '))
fileName = fileName.AppendQuotes();
if (arguments.Contains(' '))
arguments = arguments.AppendQuotes();

Process process = new()
{
Expand Down Expand Up @@ -83,10 +85,18 @@ public static async Task ProcessKill(Process? proc, bool review)

GetProcessKeyInfo(proc, review, out var procId, out var fileName, out var processName);

try { proc?.Kill(true); } catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try { proc?.Kill(); } catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try { proc?.Close(); } catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try { proc?.Dispose(); } catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try
{ proc?.Kill(true); }
catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try
{ proc?.Kill(); }
catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try
{ proc?.Close(); }
catch (Exception ex) { Logging.SaveLog(_tag, ex); }
try
{ proc?.Dispose(); }
catch (Exception ex) { Logging.SaveLog(_tag, ex); }

await Task.Delay(300);
await ProcessKillByKeyInfo(review, procId, fileName, processName);
Expand All @@ -97,7 +107,8 @@ private static void GetProcessKeyInfo(Process? proc, bool review, out int? procI
procId = null;
fileName = null;
processName = null;
if (!review) return;
if (!review)
return;
try
{
procId = proc?.Id;
Expand Down Expand Up @@ -136,4 +147,4 @@ private static async Task ProcessKillByKeyInfo(bool review, int? procId, string?
}
}
}
}
}
4 changes: 2 additions & 2 deletions v2rayN/ServiceLib/Common/SqliteHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using SQLite;
using System.Collections;
using SQLite;

namespace ServiceLib.Common
{
Expand Down Expand Up @@ -88,4 +88,4 @@ await Task.Factory.StartNew(() =>
});
}
}
}
}
10 changes: 6 additions & 4 deletions v2rayN/ServiceLib/Common/StringEx.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;

namespace ServiceLib.Common
{
Expand All @@ -21,7 +21,8 @@ public static bool IsNotEmpty([NotNullWhen(false)] this string? value)

public static bool BeginWithAny(this string s, IEnumerable<char> chars)
{
if (s.IsNullOrEmpty()) return false;
if (s.IsNullOrEmpty())
return false;
return chars.Contains(s.First());
}

Expand All @@ -34,7 +35,8 @@ public static IEnumerable<string> NonWhiteSpaceLines(this TextReader reader)
{
while (reader.ReadLine() is { } line)
{
if (line.IsWhiteSpace()) continue;
if (line.IsWhiteSpace())
continue;
yield return line;
}
}
Expand Down Expand Up @@ -69,4 +71,4 @@ public static string AppendQuotes(this string value)
return string.IsNullOrEmpty(value) ? string.Empty : $"\"{value}\"";
}
}
}
}
33 changes: 21 additions & 12 deletions v2rayN/ServiceLib/Common/Utils.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using CliWrap;
using CliWrap.Buffered;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Net;
Expand All @@ -10,6 +8,8 @@
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using CliWrap;
using CliWrap.Buffered;

namespace ServiceLib.Common
{
Expand Down Expand Up @@ -176,7 +176,8 @@ public static string Base64Decode(string? plainText)
{
try
{
if (plainText.IsNullOrEmpty()) return "";
if (plainText.IsNullOrEmpty())
return "";
plainText = plainText.Trim()
.Replace(Environment.NewLine, "")
.Replace("\n", "")
Expand Down Expand Up @@ -372,7 +373,8 @@ public static string GetPunycode(string url)

public static bool IsBase64String(string? plainText)
{
if (plainText.IsNullOrEmpty()) return false;
if (plainText.IsNullOrEmpty())
return false;
var buffer = new Span<byte>(new byte[plainText.Length]);
return Convert.TryFromBase64String(plainText, buffer, out var _);
}
Expand Down Expand Up @@ -462,9 +464,12 @@ public static bool IsPrivateNetwork(string ip)
if (IPAddress.TryParse(ip, out var address))
{
var ipBytes = address.GetAddressBytes();
if (ipBytes[0] == 10) return true;
if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) return true;
if (ipBytes[0] == 192 && ipBytes[1] == 168) return true;
if (ipBytes[0] == 10)
return true;
if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31)
return true;
if (ipBytes[0] == 192 && ipBytes[1] == 168)
return true;
}

return false;
Expand Down Expand Up @@ -604,9 +609,11 @@ public static Dictionary<string, string> GetSystemHosts()

foreach (var host in hostsList)
{
if (host.StartsWith("#")) continue;
if (host.StartsWith("#"))
continue;
var hostItem = host.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (hostItem.Length != 2) continue;
if (hostItem.Length != 2)
continue;
systemHosts.Add(hostItem.Last(), hostItem.First());
}
}
Expand Down Expand Up @@ -875,8 +882,10 @@ public static bool IsAdministrator()

public static async Task<string?> SetLinuxChmod(string? fileName)
{
if (fileName.IsNullOrEmpty()) return null;
if (fileName.Contains(' ')) fileName = fileName.AppendQuotes();
if (fileName.IsNullOrEmpty())
return null;
if (fileName.Contains(' '))
fileName = fileName.AppendQuotes();
//File.SetUnixFileMode(fileName, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
var arg = new List<string>() { "-c", $"chmod +x {fileName}" };
return await GetCliWrapOutput("/bin/bash", arg);
Expand Down Expand Up @@ -904,4 +913,4 @@ public static bool IsAdministrator()

#endregion Platform
}
}
}
32 changes: 15 additions & 17 deletions v2rayN/ServiceLib/Common/WindowsUtils.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Win32;
Expand Down Expand Up @@ -56,21 +55,20 @@ public static void RegWriteValue(string path, string name, object value)

public static async Task RemoveTunDevice()
{
try
{
var sum = MD5.HashData(Encoding.UTF8.GetBytes("wintunsingbox_tun"));
var guid = new Guid(sum);
var pnpUtilPath = @"C:\Windows\System32\pnputil.exe";
var arg = $$""" /remove-device "SWD\Wintun\{{{guid}}}" """;
try
{
var sum = MD5.HashData(Encoding.UTF8.GetBytes("wintunsingbox_tun"));
var guid = new Guid(sum);
var pnpUtilPath = @"C:\Windows\System32\pnputil.exe";
var arg = $$""" /remove-device "SWD\Wintun\{{{guid}}}" """;

// Try to remove the device
await Utils.GetCliWrapOutput(pnpUtilPath, arg);

}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}
}
}
// Try to remove the device
await Utils.GetCliWrapOutput(pnpUtilPath, arg);
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}
}
}
}
Loading

0 comments on commit 4526400

Please sign in to comment.