Skip to content

Commit

Permalink
Final Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
trudyhood committed Aug 31, 2021
1 parent 04729a6 commit 7375a24
Show file tree
Hide file tree
Showing 21 changed files with 197 additions and 204 deletions.
62 changes: 32 additions & 30 deletions Samples/VpnHood.Samples.SimpleClient.Droid/MainActivity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,22 @@
using VpnHood.Client.Device.Android;
using VpnHood.Common;
using Xamarin.Essentials;
// ReSharper disable StringLiteralTypo

namespace VpnHood.Samples.SimpleClient.Droid
{
[Activity(Label = "@string/app_name", MainLauncher = true)]
// ReSharper disable once UnusedMember.Global
public class MainActivity : Activity
{
private const int REQUEST_VpnPermission = 10;
private const int RequestVpnPermission = 10;
private static readonly AndroidDevice Device = new AndroidDevice();
private static VpnHoodClient VpnHoodClient;
private Button ConnectButton;
private TextView StatusTextView;
private static VpnHoodClient _vpnHoodClient;
private Button _connectButton;
private TextView _statusTextView;

private bool IsConnectingOrConnected =>
VpnHoodClient?.State == ClientState.Connecting || VpnHoodClient?.State == ClientState.Connected;
_vpnHoodClient?.State == ClientState.Connecting || _vpnHoodClient?.State == ClientState.Connected;

protected override void OnCreate(Bundle savedInstanceState)
{
Expand All @@ -37,14 +39,14 @@ protected override void OnCreate(Bundle savedInstanceState)
// Set our simple view
var linearLayout = new LinearLayout(this);

ConnectButton = new Button(this);
ConnectButton.Click += ConnectButton_Click;
linearLayout.AddView(ConnectButton);
_connectButton = new Button(this);
_connectButton.Click += ConnectButton_Click;
linearLayout.AddView(_connectButton);

StatusTextView = new TextView(this);
linearLayout.AddView(StatusTextView);
_statusTextView = new TextView(this);
linearLayout.AddView(_statusTextView);
SetContentView(linearLayout);
UpdateUI();
UpdateUi();
}

private void ConnectButton_Click(object sender, EventArgs e)
Expand All @@ -68,42 +70,42 @@ private async Task ConnectTask()
var token = Token.FromAccessKey(accessKey);
var packetCapture = await Device.CreatePacketCapture();

VpnHoodClient = new VpnHoodClient(packetCapture, clientId, token, new ClientOptions());
VpnHoodClient.StateChanged += (object sender, EventArgs e) => UpdateUI();
await VpnHoodClient.Connect();
_vpnHoodClient = new VpnHoodClient(packetCapture, clientId, token, new ClientOptions());
_vpnHoodClient.StateChanged += (sender, e) => UpdateUi();
await _vpnHoodClient.Connect();
}
catch (Exception ex)
{
var str = ex.Message;
Console.WriteLine(ex.Message);
}
}

private void Disconnect()
{
VpnHoodClient?.Dispose();
VpnHoodClient = null;
_vpnHoodClient?.Dispose();
_vpnHoodClient = null;
}


private void UpdateUI()
private void UpdateUi()
{
MainThread.BeginInvokeOnMainThread(() =>
{
if (VpnHoodClient == null || VpnHoodClient.State == ClientState.None ||
VpnHoodClient.State == ClientState.Disposed)
if (_vpnHoodClient == null || _vpnHoodClient.State == ClientState.None ||
_vpnHoodClient.State == ClientState.Disposed)
{
ConnectButton.Text = "Connect";
StatusTextView.Text = "Disconnected";
_connectButton.Text = "Connect";
_statusTextView.Text = "Disconnected";
}
else if (VpnHoodClient.State == ClientState.Connecting)
else if (_vpnHoodClient.State == ClientState.Connecting)
{
ConnectButton.Text = "Disconnect";
StatusTextView.Text = "Connecting";
_connectButton.Text = "Disconnect";
_statusTextView.Text = "Connecting";
}
else if (VpnHoodClient.State == ClientState.Connected)
else if (_vpnHoodClient.State == ClientState.Connected)
{
ConnectButton.Text = "Disconnect";
StatusTextView.Text = "Connected";
_connectButton.Text = "Disconnect";
_statusTextView.Text = "Connected";
}
});
}
Expand All @@ -117,13 +119,13 @@ private void Device_OnRequestVpnPermission(object sender, EventArgs e)
}
else
{
StartActivityForResult(intent, REQUEST_VpnPermission);
StartActivityForResult(intent, RequestVpnPermission);
}
}

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if (requestCode == REQUEST_VpnPermission && resultCode == Result.Ok)
if (requestCode == RequestVpnPermission && resultCode == Result.Ok)
Device.VpnPermissionGranted();
else
Device.VpnPermissionRejected();
Expand Down
1 change: 1 addition & 0 deletions Samples/VpnHood.Samples.SimpleClient.Win/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using VpnHood.Client;
using VpnHood.Client.Device.WinDivert;
using VpnHood.Common;
// ReSharper disable StringLiteralTypo

namespace VpnHood.Samples.SimpleClient.Win
{
Expand Down
18 changes: 8 additions & 10 deletions VpnHood.App.Launcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ namespace VpnHood.App.Launcher
{
internal class Program
{
private static readonly ILogger _logger = NullLogger.Instance;
private static readonly ILogger Logger = NullLogger.Instance;

private static int Main(string[] args)
{
if (args == null) args = Array.Empty<string>();

// set sessionName from -launcher:sessionName:
var sessionName = FindSessionName(args);
if (!string.IsNullOrEmpty(sessionName))
Expand All @@ -36,14 +34,14 @@ private static int Main(string[] args)

string appFolder = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)) ??
throw new Exception($"Could not find {nameof(appFolder)}!");
using Updater _updater = new(appFolder, new UpdaterOptions {Logger = new SimpleLogger()});
var res = _updater.Start();
using Updater updater = new(appFolder, new UpdaterOptions {Logger = new SimpleLogger()});
var res = updater.Start();
return res;
}

private static string? FindSessionName(string[] args)
{
// get laucnher sessionName
// get launcher sessionName
var key = "-launcher:sessionName:";
var sessionArg = args.FirstOrDefault(x => x.IndexOf(key, StringComparison.OrdinalIgnoreCase) == 0);

Expand All @@ -67,23 +65,23 @@ private static int Update(string[] args)

public static int Update(string zipFile, string destination, string[] dotnetArgs)
{
_logger.LogInformation("Preparing for extraction...");
Logger.LogInformation("Preparing for extraction...");
Thread.Sleep(3000);

// unzip
try
{
_logger.LogInformation($"Extracting '{zipFile}' to '{destination}'...");
Logger.LogInformation($"Extracting '{zipFile}' to '{destination}'...");
ZipFile.ExtractToDirectory(zipFile, destination, true);
if (File.Exists(zipFile)) File.Delete(zipFile);
}
catch (Exception ex)
{
_logger.LogError($"Could not extract! Error: {ex.Message}");
Logger.LogError($"Could not extract! Error: {ex.Message}");
}

// launch updated app
if (dotnetArgs != null && dotnetArgs.Length > 0 && !dotnetArgs.Contains("-launcher:noLaunchAfterUpdate"))
if (dotnetArgs.Length > 0 && !dotnetArgs.Contains("-launcher:noLaunchAfterUpdate"))
{
// create processStartInfo
var processStartInfo = new ProcessStartInfo
Expand Down
2 changes: 1 addition & 1 deletion VpnHood.App.Launcher/PublishInfo.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace VpnHood.Common
namespace VpnHood.App.Launcher
{
public class PublishInfo
{
Expand Down
47 changes: 23 additions & 24 deletions VpnHood.App.Launcher/Updater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using VpnHood.Common;

namespace VpnHood.App.Launcher
{
Expand All @@ -24,7 +23,7 @@ public class Updater : IDisposable

public Updater(string? appFolder = null, UpdaterOptions? options = null)
{
if (options == null) options = new UpdaterOptions();
options ??= new UpdaterOptions();
_logger = options.Logger;
AppFolder = appFolder
?? Path.GetDirectoryName(Path.GetDirectoryName(typeof(Updater).Assembly.Location))
Expand Down Expand Up @@ -58,7 +57,7 @@ public Updater(string? appFolder = null, UpdaterOptions? options = null)
public string NewPublishInfoFilePath => Path.Combine(UpdatesFolder, "publish.json");
private string LastCheckFilePath => Path.Combine(UpdatesFolder, "lastcheck.json");
public PublishInfo PublishInfo { get; }
public CancellationToken CancelationToken => _cancellationTokenSource.Token;
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
public bool IsStarted { get; private set; }

public DateTime? LastOnlineCheckTime
Expand All @@ -75,6 +74,7 @@ public DateTime? LastOnlineCheckTime
}
catch
{
// ignored
}

return null;
Expand Down Expand Up @@ -109,10 +109,10 @@ public int Start()

// Create Update Interval
if (UpdateUri != null && CheckIntervalMinutes != 0)
_timer = new Timer(state => CheckUpdateOnlineInterval(), null, 0, CheckIntervalMinutes * 60 * 1000);
_timer = new Timer(_ => CheckUpdateOnlineInterval(), null, 0, CheckIntervalMinutes * 60 * 1000);

// launch main app
if (!CancelationToken.IsCancellationRequested)
if (!CancellationToken.IsCancellationRequested)
return Launch();

return -2;
Expand All @@ -139,18 +139,18 @@ public async Task CheckUpdateOnline()

// read online version
using var httpClient = new HttpClient {Timeout = TimeSpan.FromMilliseconds(10000)};
var onlinePublishInfoJson = await httpClient.GetStringAsync(UpdateUri);
var onlinePublishInfoJson = await httpClient.GetStringAsync(UpdateUri, CancellationToken);
var onlinePublishInfo = JsonSerializer.Deserialize<PublishInfo>(onlinePublishInfoJson) ??
throw new Exception($"Could not load {nameof(PublishInfo)}!");
_logger.LogInformation(
$"CurrentVersion: {PublishInfo.Version}, OnlineVersion: {onlinePublishInfo.Version}");

// check targetFramework
var isSameTargetFramework =
CompareTragetFramework(onlinePublishInfo.TargetFramework, PublishInfo.TargetFramework) == 0;
CompareTargetFramework(onlinePublishInfo.TargetFramework, PublishInfo.TargetFramework) == 0;
if (!isSameTargetFramework)
_logger.LogWarning(
$"Thre is an update that requires a new DotNet Framework. Consider full upgrade. Current TargetFramework: {PublishInfo.TargetFramework}, TargetFramework: {onlinePublishInfo.TargetFramework}");
$"There is an update that requires a new DotNet Framework. Consider full upgrade. Current TargetFramework: {PublishInfo.TargetFramework}, TargetFramework: {onlinePublishInfo.TargetFramework}");

// download if newer
var curVer = Version.Parse(PublishInfo.Version);
Expand All @@ -159,7 +159,7 @@ public async Task CheckUpdateOnline()
await DownloadUpdate(onlinePublishInfo);

//write lastCheckTime
File.WriteAllText(LastCheckFilePath, JsonSerializer.Serialize(DateTime.Now));
await File.WriteAllTextAsync(LastCheckFilePath, JsonSerializer.Serialize(DateTime.Now), CancellationToken);
}

private void CheckUpdateOffline()
Expand Down Expand Up @@ -188,7 +188,7 @@ private async Task DownloadUpdate(PublishInfo publishInfo)

// open source stream from net
using var httpClient = new HttpClient {Timeout = TimeSpan.FromMilliseconds(10000)};
await using var srcStream = await httpClient.GetStreamAsync(publishInfo.PackageDownloadUrl);
await using var srcStream = await httpClient.GetStreamAsync(publishInfo.PackageDownloadUrl, CancellationToken);

// create desStream
if (string.IsNullOrEmpty(publishInfo.PackageFileName))
Expand All @@ -198,11 +198,11 @@ private async Task DownloadUpdate(PublishInfo publishInfo)
await using var desStream = File.Create(desFilePath);

// download
await srcStream.CopyToAsync(desStream);
await srcStream.CopyToAsync(desStream, CancellationToken);
await desStream.DisposeAsync(); //release lock as soon as possible

// set update file
File.WriteAllText(NewPublishInfoFilePath, JsonSerializer.Serialize(publishInfo));
await File.WriteAllTextAsync(NewPublishInfoFilePath, JsonSerializer.Serialize(publishInfo), CancellationToken);
}

private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
Expand All @@ -227,14 +227,13 @@ private static string ReadAllTextAndWait(string fileName, long retry = 5)
throw exception;
}

private static int CompareTragetFramework(string targetFramework1, string targetFramework2)
private static int CompareTargetFramework(string targetFramework1, string targetFramework2)
{
if (string.IsNullOrWhiteSpace(targetFramework1) || string.IsNullOrWhiteSpace(targetFramework2))
return -1;

var t1 = Version.Parse(Regex.Replace(targetFramework1, "[^0-9.]", ""));
var t2 = Version.Parse(Regex.Replace(targetFramework2, "[^0-9.]", ""));
;
var tt1 = new Version(t1.Major, t1.Minor);
var tt2 = new Version(t2.Major, t2.Minor);
return tt1.CompareTo(tt2);
Expand Down Expand Up @@ -266,7 +265,7 @@ private void ExitAndLaunchUpdater()
$"The update file is not a newer version! CurrentVersion: {curVersion}, UpdateVersion: {version}");

// check dotnet version
if (CompareTragetFramework(newPublishInfo.TargetFramework, PublishInfo.TargetFramework) != 0)
if (CompareTargetFramework(newPublishInfo.TargetFramework, PublishInfo.TargetFramework) != 0)
throw new Exception(
$"The update requires new DotNet Framework. Consider full upgrade. Current TargetFramework: {PublishInfo.TargetFramework}, TargetFramework: {newPublishInfo.TargetFramework}");

Expand All @@ -275,9 +274,9 @@ private void ExitAndLaunchUpdater()
var tempLauncherFilePath = Path.Combine(tempLaunchFolder, "run.dll");
_logger.LogInformation($"Preparing updater. {tempLaunchFolder}");
if (Directory.Exists(tempLaunchFolder)) Directory.Delete(tempLaunchFolder, true);
var updaterSssemlyLocation = Path.GetDirectoryName(typeof(Updater).Assembly.Location) ??
throw new Exception("Could not find update assembbly location!");
DirectoryCopy(updaterSssemlyLocation, tempLaunchFolder, true);
var updaterAssemblyLocation = Path.GetDirectoryName(typeof(Updater).Assembly.Location) ??
throw new Exception("Could not find update assembly location!");
DirectoryCopy(updaterAssemblyLocation, tempLaunchFolder, true);

// dotnet tempdir/launcher.dll update package.zip appFolder orgArguments
var args = new[] {tempLauncherFilePath, "update", packageFile, AppFolder};
Expand Down Expand Up @@ -328,7 +327,7 @@ private int Launch()
args = args.Concat(Environment.GetCommandLineArgs()[1..]);

// remove launcher arguments
args = args.Where(x => x.IndexOf("-launcher:") != 0);
args = args.Where(x => x.IndexOf("-launcher:", StringComparison.Ordinal) != 0);

// remove duplicates
foreach (var arg in args)
Expand All @@ -338,11 +337,11 @@ private int Launch()
// Start process
var process = Process.Start(processStartInfo) ??
throw new Exception($"Could not start {processStartInfo.FileName}!");
var task = process.WaitForExitAsync(CancelationToken);
var task = process.WaitForExitAsync(CancellationToken);

try
{
task.Wait(CancelationToken);
task.Wait(CancellationToken);
return process.ExitCode;
}
catch (OperationCanceledException)
Expand Down Expand Up @@ -380,10 +379,10 @@ private static void DirectoryCopy(string sourceDirName, string destDirName, bool

// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
foreach (var subdir in dirs)
foreach (var item in dirs)
{
var tempPath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, tempPath, copySubDirs);
var tempPath = Path.Combine(destDirName, item.Name);
DirectoryCopy(item.FullName, tempPath, copySubDirs);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions VpnHood.Client.App.Android/MainActivity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ namespace VpnHood.Client.App.Android
public class MainActivity : Activity
{
private const int RequestVpnPermission = 10;
private VpnHoodAppUI? _appUi;
private VpnHoodAppUi? _appUi;

private AndroidDevice Device => (AndroidDevice?) AndroidApp.Current?.Device ??
throw new InvalidOperationException($"{nameof(Device)} is not initialized!");
Expand All @@ -48,7 +48,7 @@ protected override void OnCreate(Bundle? savedInstanceState)
// Initialize UI
var zipStream = Resources?.Assets?.Open("SPA.zip") ??
throw new Exception("Could not load SPA.zip resource!");
_appUi = VpnHoodAppUI.Init(zipStream);
_appUi = VpnHoodAppUi.Init(zipStream);
InitWebUi();
}

Expand Down
Loading

0 comments on commit 7375a24

Please sign in to comment.