From 21abb44230598bdad1d0be6097e88e7e43dc6dca Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Thu, 21 Apr 2022 07:33:26 +0200 Subject: [PATCH 01/10] Add rule to ignore the warning: `Mark members as static` to `.editorconfig` --- .editorconfig | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.editorconfig b/.editorconfig index 83a9726..6f0a5d6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,3 +2,9 @@ # S4457: Parameter validation in "async"/"await" methods should be wrapped dotnet_diagnostic.S4457.severity = silent + +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = silent + +# S1172: Unused method parameters should be removed +dotnet_diagnostic.S1172.severity = silent From 495a09ec6024825b579bd170aa743dd13647e792 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Thu, 21 Apr 2022 07:34:28 +0200 Subject: [PATCH 02/10] Update naming and add auto retry if hash is wrong --- .../{UserInterface => }/InputHandler.cs | 2 +- HyperbolicDownloader/Program.cs | 1 - .../Commands/ClientCommands.cs | 10 ++-- .../Commands/DownloadCommands.cs | 49 ++++++++++--------- .../Commands/FileCommands.cs | 42 ++++++++-------- .../Commands/HostCommands.cs | 46 ++++++++--------- .../Managment/ApiManager.cs | 24 ++++----- .../Networking/BroadcastClient.cs | 4 +- .../Networking/HostsManager.cs | 8 +-- 9 files changed, 93 insertions(+), 93 deletions(-) rename HyperbolicDownloader/{UserInterface => }/InputHandler.cs (98%) diff --git a/HyperbolicDownloader/UserInterface/InputHandler.cs b/HyperbolicDownloader/InputHandler.cs similarity index 98% rename from HyperbolicDownloader/UserInterface/InputHandler.cs rename to HyperbolicDownloader/InputHandler.cs index acd0ea6..d7ca1df 100644 --- a/HyperbolicDownloader/UserInterface/InputHandler.cs +++ b/HyperbolicDownloader/InputHandler.cs @@ -5,7 +5,7 @@ using HyperbolicDownloaderApi.FileProcessing; using Stone_Red_Utilities.ConsoleExtentions; -namespace HyperbolicDownloaderApi.UserInterface; +namespace HyperbolicDownloaderApi; internal class InputHandler { diff --git a/HyperbolicDownloader/Program.cs b/HyperbolicDownloader/Program.cs index e99036c..7c52a91 100644 --- a/HyperbolicDownloader/Program.cs +++ b/HyperbolicDownloader/Program.cs @@ -1,7 +1,6 @@ using HyperbolicDownloaderApi.FileProcessing; using HyperbolicDownloaderApi.Managment; using HyperbolicDownloaderApi.Networking; -using HyperbolicDownloaderApi.UserInterface; using Stone_Red_Utilities.ConsoleExtentions; diff --git a/HyperbolicDownloaderApi/Commands/ClientCommands.cs b/HyperbolicDownloaderApi/Commands/ClientCommands.cs index c7f91ad..3cc6b73 100644 --- a/HyperbolicDownloaderApi/Commands/ClientCommands.cs +++ b/HyperbolicDownloaderApi/Commands/ClientCommands.cs @@ -9,12 +9,12 @@ public class ClientCommands { if (ApiManager.PublicIpAddress is not null) { - ApiManager.SendMessageNewLine($"The public IP address is: {ApiManager.PublicIpAddress}", NotificationMessageType.Info); - ApiManager.SendMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Info); - ApiManager.SendMessageNewLine(string.Empty, NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"The public IP address is: {ApiManager.PublicIpAddress}", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine(string.Empty, NotificationMessageType.Info); } - ApiManager.SendMessageNewLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()}", NotificationMessageType.Info); - ApiManager.SendMessageNewLine($"The private port is: {ApiConfiguration.PrivatePort}", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()}", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"The private port is: {ApiConfiguration.PrivatePort}", NotificationMessageType.Info); } } \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Commands/DownloadCommands.cs b/HyperbolicDownloaderApi/Commands/DownloadCommands.cs index 7b51d8f..04ec861 100644 --- a/HyperbolicDownloaderApi/Commands/DownloadCommands.cs +++ b/HyperbolicDownloaderApi/Commands/DownloadCommands.cs @@ -27,7 +27,7 @@ public class DownloadCommands { if (string.IsNullOrWhiteSpace(path)) { - ApiManager.SendMessageNewLine("Path is empty!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Path is empty!", NotificationMessageType.Error); return; } @@ -35,7 +35,7 @@ public class DownloadCommands if (!File.Exists(fullPath)) { - ApiManager.SendMessageNewLine("Invalid file path!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid file path!", NotificationMessageType.Error); } string json = File.ReadAllText(fullPath); @@ -43,7 +43,7 @@ public class DownloadCommands PublicHyperFileInfo? publicHyperFileInfo = JsonSerializer.Deserialize(json); if (publicHyperFileInfo == null) { - ApiManager.SendMessageNewLine("Parsing file failed!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Parsing file failed!", NotificationMessageType.Error); return; } @@ -55,7 +55,7 @@ public class DownloadCommands { if (string.IsNullOrEmpty(hash)) { - ApiManager.SendMessageNewLine("No hash value specified!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("No hash value specified!", NotificationMessageType.Error); return; } @@ -71,7 +71,7 @@ public class DownloadCommands continue; } - ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning); + ApiManager.SendNotificationMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning); Console.CursorLeft = 0; @@ -82,7 +82,7 @@ public class DownloadCommands if (!sendTask.IsCompletedSuccessfully) { Console.CursorLeft = 0; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); hostsManager.Remove(host); continue; @@ -90,14 +90,14 @@ public class DownloadCommands else if (!sendTask.Result) { host.LastActive = DateTime.Now; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Does not have the requested file", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Does not have the requested file", NotificationMessageType.Error); continue; } host.LastActive = DateTime.Now; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Has the requested file", NotificationMessageType.Success); - ApiManager.SendMessageNewLine("Requesting file..."); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Has the requested file", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine("Requesting file..."); using TcpClient tcpClient = new TcpClient(); tcpClient.Connect(ipAddress!, host.Port); @@ -118,8 +118,8 @@ public class DownloadCommands } catch (IOException) { - ApiManager.SendMessageNewLine(string.Empty); - ApiManager.SendMessageNewLine("Lost connection to other host!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine(string.Empty); + ApiManager.SendNotificationMessageNewLine("Lost connection to other host!", NotificationMessageType.Error); continue; } @@ -129,7 +129,7 @@ public class DownloadCommands if (parts.Length != 2) //If received data does not contain 2 parts -> error { - ApiManager.SendMessageNewLine(dataReceived, NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine(dataReceived, NotificationMessageType.Error); continue; } @@ -137,7 +137,7 @@ public class DownloadCommands if (!validFileSize || fileSize <= 0) { - ApiManager.SendMessageNewLine("Invalid file size!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid file size!", NotificationMessageType.Error); continue; } @@ -145,8 +145,8 @@ public class DownloadCommands string directoryPath = Path.Combine(ApiConfiguration.BasePath, "Downloads"); string filePath = Path.Combine(directoryPath, fileName); - ApiManager.SendMessageNewLine($"File name: {fileName}"); - ApiManager.SendMessageNewLine($"Starting download..."); + ApiManager.SendNotificationMessageNewLine($"File name: {fileName}"); + ApiManager.SendNotificationMessageNewLine($"Starting download..."); int totalBytesRead = 0; @@ -172,8 +172,8 @@ public class DownloadCommands catch (IOException ex) { Debug.WriteLine(ex); - ApiManager.SendMessageNewLine(string.Empty); - ApiManager.SendMessageNewLine("Lost connection to other host!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine(string.Empty); + ApiManager.SendNotificationMessageNewLine("Lost connection to other host!", NotificationMessageType.Error); break; } @@ -201,7 +201,7 @@ public class DownloadCommands stopWatch.Restart(); } - ApiManager.SendMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] "); + ApiManager.SendNotificationMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] "); } fileStream.Close(); @@ -211,25 +211,26 @@ public class DownloadCommands continue; } - ApiManager.SendMessageNewLine(string.Empty); + ApiManager.SendNotificationMessageNewLine(string.Empty); - ApiManager.SendMessageNewLine("Validating file..."); + ApiManager.SendNotificationMessageNewLine("Validating file..."); if (FileValidator.ValidateHash(filePath, hash)) { _ = filesManager.TryAdd(filePath, out _, out _); } else { - ApiManager.SendMessageNewLine("Warning: File hash does not match! File might me corrupted or manipulated!", NotificationMessageType.Warning); + ApiManager.SendNotificationMessageNewLine("Warning: File hash does not match! File might me corrupted or manipulated! Trying next host...", NotificationMessageType.Warning); + continue; } - ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); - ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); + ApiManager.SendNotificationMessageNewLine("Done", NotificationMessageType.Success); stopWatch.Stop(); hostsManager.SaveHosts(); return; } - ApiManager.SendMessageNewLine("None of the available hosts have the requested file!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("None of the available hosts have the requested file!", NotificationMessageType.Error); hostsManager.SaveHosts(); } } \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Commands/FileCommands.cs b/HyperbolicDownloaderApi/Commands/FileCommands.cs index 0d94ddb..960daa5 100644 --- a/HyperbolicDownloaderApi/Commands/FileCommands.cs +++ b/HyperbolicDownloaderApi/Commands/FileCommands.cs @@ -23,12 +23,12 @@ public class FileCommands { if (filesManager.TryAdd(path, out PrivateHyperFileInfo? fileInfo, out string? message)) { - ApiManager.SendMessageNewLine($"Added file: {fileInfo!.FilePath}", NotificationMessageType.Success); - ApiManager.SendMessageNewLine($"Hash: {fileInfo.Hash}"); + ApiManager.SendNotificationMessageNewLine($"Added file: {fileInfo!.FilePath}", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"Hash: {fileInfo.Hash}"); } else { - ApiManager.SendMessageNewLine(message!, NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine(message!, NotificationMessageType.Error); } } @@ -38,11 +38,11 @@ public class FileCommands if (filesManager.TryRemove(hash)) { - ApiManager.SendMessageNewLine($"Successfully removed file!", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"Successfully removed file!", NotificationMessageType.Success); } else { - ApiManager.SendMessageNewLine("The file is not being tracked!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("The file is not being tracked!", NotificationMessageType.Error); } } @@ -53,16 +53,16 @@ public class FileCommands if (fileInfos.Count == 0) { - ApiManager.SendMessageNewLine("No tracked files!", NotificationMessageType.Warning); + ApiManager.SendNotificationMessageNewLine("No tracked files!", NotificationMessageType.Warning); return; } foreach (PrivateHyperFileInfo fileInfo in fileInfos) { index++; - ApiManager.SendMessageNewLine($"{index}) {fileInfo.FilePath}"); - ApiManager.SendMessageNewLine($"Hash: {fileInfo.Hash}"); - ApiManager.SendMessageNewLine(string.Empty); + ApiManager.SendNotificationMessageNewLine($"{index}) {fileInfo.FilePath}"); + ApiManager.SendNotificationMessageNewLine($"Hash: {fileInfo.Hash}"); + ApiManager.SendNotificationMessageNewLine(string.Empty); } Console.CursorTop--; } @@ -79,7 +79,7 @@ public class FileCommands if (!filesManager.TryGet(hash, out PrivateHyperFileInfo? localHyperFileInfo)) { - ApiManager.SendMessageNewLine("The file is not being tracked!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("The file is not being tracked!", NotificationMessageType.Error); return; } @@ -91,7 +91,7 @@ public class FileCommands NetworkSocket? localHost = ApiManager.GetLocalSocket(); if (localHost is null) { - ApiManager.SendMessageNewLine("Network error!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Network error!", NotificationMessageType.Error); return; } @@ -102,8 +102,8 @@ public class FileCommands File.WriteAllText(filePath, json); - ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success); - ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); + ApiManager.SendNotificationMessageNewLine("Done", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); } public void GenerateFileFull(string hash) @@ -118,7 +118,7 @@ public class FileCommands if (!filesManager.TryGet(hash, out PrivateHyperFileInfo? localHyperFileInfo)) { - ApiManager.SendMessageNewLine("The file is not being tracked!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("The file is not being tracked!", NotificationMessageType.Error); return; } @@ -130,7 +130,7 @@ public class FileCommands NetworkSocket? localHost = ApiManager.GetLocalSocket(); if (localHost is null) { - ApiManager.SendMessageNewLine("Network error!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Network error!", NotificationMessageType.Error); return; } @@ -144,7 +144,7 @@ public class FileCommands continue; } - ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning); + ApiManager.SendNotificationMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning); Console.CursorLeft = 0; @@ -155,7 +155,7 @@ public class FileCommands if (!sendTask.IsCompletedSuccessfully) { Console.CursorLeft = 0; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); hostsManager.Remove(host); continue; @@ -163,13 +163,13 @@ public class FileCommands else if (!sendTask.Result) { host.LastActive = DateTime.Now; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Does not have the requested file", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Does not have the requested file", NotificationMessageType.Error); continue; } host.LastActive = DateTime.Now; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Has the requested file", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Has the requested file", NotificationMessageType.Success); publicHyperFileInfo.Hosts.Add(host); } @@ -180,7 +180,7 @@ public class FileCommands File.WriteAllText(filePath, json); - ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success); - ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); + ApiManager.SendNotificationMessageNewLine("Done", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); } } \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Commands/HostCommands.cs b/HyperbolicDownloaderApi/Commands/HostCommands.cs index 1f20919..3e4ee1a 100644 --- a/HyperbolicDownloaderApi/Commands/HostCommands.cs +++ b/HyperbolicDownloaderApi/Commands/HostCommands.cs @@ -18,7 +18,7 @@ public class HostCommands public void Discover(string _) { - ApiManager.SendMessageNewLine("Running local discovery routine...", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine("Running local discovery routine...", NotificationMessageType.Info); BroadcastClient.Send(ApiConfiguration.BroadcastPort, ApiConfiguration.PrivatePort.ToString()); Thread.Sleep(3000); } @@ -28,13 +28,13 @@ public class HostCommands int activeHostsCount = hostsManager.CheckHostsActivity(); if (activeHostsCount == 0) { - ApiManager.SendMessageNewLine("No active hosts found!", NotificationMessageType.Error); - ApiManager.SendMessageNewLine("Use 'add host xxx.xxx.xxx.xxx:yyyy' to add a new host.", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("No active hosts found!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Use 'add host xxx.xxx.xxx.xxx:yyyy' to add a new host.", NotificationMessageType.Error); } - ApiManager.SendMessageNewLine(string.Empty, NotificationMessageType.Info); - ApiManager.SendMessageNewLine($"{hostsManager.Count} known host(s).", NotificationMessageType.Info); - ApiManager.SendMessageNewLine($"{activeHostsCount} active host(s).", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine(string.Empty, NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"{hostsManager.Count} known host(s).", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"{activeHostsCount} active host(s).", NotificationMessageType.Info); } public void ListHosts(string _) @@ -44,16 +44,16 @@ public class HostCommands if (hosts.Count == 0) { - ApiManager.SendMessageNewLine("No known hosts", NotificationMessageType.Warning); + ApiManager.SendNotificationMessageNewLine("No known hosts", NotificationMessageType.Warning); return; } foreach (NetworkSocket host in hosts) { index++; - ApiManager.SendMessageNewLine($"{index}) {host.IPAddress}:{host.Port}", NotificationMessageType.Info); - ApiManager.SendMessageNewLine($"Last active: {host.LastActive}", NotificationMessageType.Info); - ApiManager.SendMessageNewLine(string.Empty, NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"{index}) {host.IPAddress}:{host.Port}", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine($"Last active: {host.LastActive}", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine(string.Empty, NotificationMessageType.Info); } Console.CursorTop--; } @@ -64,7 +64,7 @@ public class HostCommands if (parts.Length != 2) { - ApiManager.SendMessageNewLine("Invalid format! Use this format: (xxx.xxx.xxx.xxx:yyyy)", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid format! Use this format: (xxx.xxx.xxx.xxx:yyyy)", NotificationMessageType.Error); return; } @@ -74,13 +74,13 @@ public class HostCommands _ = int.TryParse(portInput, out int port); if (port < 1000 || port >= 6000) { - ApiManager.SendMessageNewLine("Invalid port number!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid port number!", NotificationMessageType.Error); return; } if (!IPAddress.TryParse(ipAddressInput, out IPAddress? ipAddress)) { - ApiManager.SendMessageNewLine("Invalid IP address!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid IP address!", NotificationMessageType.Error); return; } @@ -88,12 +88,12 @@ public class HostCommands if (!hostsManager.Contains(hostToRemove)) { - ApiManager.SendMessageNewLine("Host not in list", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Host not in list", NotificationMessageType.Error); return; } hostsManager.Remove(new NetworkSocket(ipAddress.ToString(), port, DateTime.MinValue), true); - ApiManager.SendMessageNewLine($"Successfully Removed host!", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"Successfully Removed host!", NotificationMessageType.Success); } public void AddHost(string args) @@ -102,7 +102,7 @@ public class HostCommands if (parts.Length != 2) { - ApiManager.SendMessageNewLine("Invalid format! Use this format: (xxx.xxx.xxx.xxx:yyyy)", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid format! Use this format: (xxx.xxx.xxx.xxx:yyyy)", NotificationMessageType.Error); return; } @@ -114,7 +114,7 @@ public class HostCommands if (port < 1000 || port >= 6000) { - ApiManager.SendMessageNewLine("Invalid port number!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid port number!", NotificationMessageType.Error); return; } else if (!IPAddress.TryParse(ipAddressInput, out ipAddress)) @@ -131,33 +131,33 @@ public class HostCommands if (ipAddress is null) { - ApiManager.SendMessageNewLine("Invalid IP address!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Invalid IP address!", NotificationMessageType.Error); return; } try { - ApiManager.SendMessageNewLine("Waiting for response...", NotificationMessageType.Info); + ApiManager.SendNotificationMessageNewLine("Waiting for response...", NotificationMessageType.Info); NetworkSocket? localSocket = ApiManager.GetLocalSocket() ?? new NetworkSocket("0.0.0.0", 0, DateTime.MinValue); List? recivedHosts = NetworkClient.Send>(ipAddress, port, "GetHostsList", localSocket); if (recivedHosts is not null) { - ApiManager.SendMessageNewLine($"Success! Added {recivedHosts.Count} new host(s).", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"Success! Added {recivedHosts.Count} new host(s).", NotificationMessageType.Success); hostsManager.AddRange(recivedHosts); } else { - ApiManager.SendMessageNewLine($"Invalid response!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"Invalid response!", NotificationMessageType.Error); } } catch (SocketException ex) { - ApiManager.SendMessageNewLine($"Invalid host! Error message: {ex.Message}", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"Invalid host! Error message: {ex.Message}", NotificationMessageType.Error); } catch (IOException ex) { - ApiManager.SendMessageNewLine($"Invalid host! Error message: {ex.Message}", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"Invalid host! Error message: {ex.Message}", NotificationMessageType.Error); } } } \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Managment/ApiManager.cs b/HyperbolicDownloaderApi/Managment/ApiManager.cs index c0abc8f..aeb485d 100644 --- a/HyperbolicDownloaderApi/Managment/ApiManager.cs +++ b/HyperbolicDownloaderApi/Managment/ApiManager.cs @@ -62,30 +62,30 @@ public class ApiManager device = await discoverer.DiscoverDeviceAsync(); IPAddress? ip = await device.GetExternalIPAsync(); - SendMessageNewLine($"The public IP address is: {ip} ", NotificationMessageType.Success); + SendNotificationMessageNewLine($"The public IP address is: {ip} ", NotificationMessageType.Success); portMapping = new Mapping(Protocol.Tcp, ApiConfiguration.PrivatePort, ApiConfiguration.PublicPort, "HyperbolicDowloader"); await device.CreatePortMapAsync(portMapping); - SendMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Success); + SendNotificationMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Success); return true; } catch (NatDeviceNotFoundException) { - SendMessageNewLine($"Could not find a UPnP or NAT-PMP device!", NotificationMessageType.Error); + SendNotificationMessageNewLine($"Could not find a UPnP or NAT-PMP device!", NotificationMessageType.Error); return false; } catch (MappingException ex) { - SendMessageNewLine($"An error occurred while mapping the private port ({ApiConfiguration.PrivatePort}) to the public port ({ApiConfiguration.PublicPort})! Error message: {ex.Message}", NotificationMessageType.Error); + SendNotificationMessageNewLine($"An error occurred while mapping the private port ({ApiConfiguration.PrivatePort}) to the public port ({ApiConfiguration.PublicPort})! Error message: {ex.Message}", NotificationMessageType.Error); return false; } } public static void ClosePorts() { - SendMessageNewLine("Closing ports...", NotificationMessageType.Info); + SendNotificationMessageNewLine("Closing ports...", NotificationMessageType.Info); if (device is not null) { try @@ -101,11 +101,11 @@ public class ApiManager } catch (Exception ex) { - SendMessageNewLine(ex.ToString(), NotificationMessageType.Error); + SendNotificationMessageNewLine(ex.ToString(), NotificationMessageType.Error); } } - SendMessageNewLine("Ports closed!", NotificationMessageType.Warning); + SendNotificationMessageNewLine("Ports closed!", NotificationMessageType.Warning); Environment.Exit(0); } @@ -127,7 +127,7 @@ public class ApiManager } catch (SocketException ex) { - SendMessageNewLine($"An error occurred while starting the TCP listener! Error message: {ex.Message}", NotificationMessageType.Error); // net stop hens && net start hns + SendNotificationMessageNewLine($"An error occurred while starting the TCP listener! Error message: {ex.Message}", NotificationMessageType.Error); // net stop hens && net start hns Console.ReadKey(); } } @@ -165,7 +165,7 @@ public class ApiManager private void DiscoverAnswer(object? sender, MessageRecivedEventArgs> recivedEventArgs) { - SendMessageNewLine($"Received answer from {recivedEventArgs.IpAddress}. Returned {recivedEventArgs.Data.Count} host(s).", NotificationMessageType.Info); + SendNotificationMessageNewLine($"Received answer from {recivedEventArgs.IpAddress}. Returned {recivedEventArgs.Data.Count} host(s).", NotificationMessageType.Info); HostsManager.AddRange(recivedEventArgs.Data); } @@ -198,15 +198,15 @@ public class ApiManager private void ReciveMessage(object? sender, MessageRecivedEventArgs recivedEventArgs) { - SendMessageNewLine($"Received \"{recivedEventArgs.Data}\" from {recivedEventArgs.IpAddress}.", NotificationMessageType.Info); + SendNotificationMessageNewLine($"Received \"{recivedEventArgs.Data}\" from {recivedEventArgs.IpAddress}.", NotificationMessageType.Info); } - internal static void SendMessage(string message, NotificationMessageType messageType = NotificationMessageType.Info) + internal static void SendNotificationMessage(string message, NotificationMessageType messageType = NotificationMessageType.Info) { OnNotificationMessageRecived?.Invoke(null, new NotificationMessageEventArgs(messageType, message)); } - internal static void SendMessageNewLine(string message, NotificationMessageType messageType = NotificationMessageType.Info) + internal static void SendNotificationMessageNewLine(string message, NotificationMessageType messageType = NotificationMessageType.Info) { OnNotificationMessageRecived?.Invoke(null, new NotificationMessageEventArgs(messageType, message + Environment.NewLine)); } diff --git a/HyperbolicDownloaderApi/Networking/BroadcastClient.cs b/HyperbolicDownloaderApi/Networking/BroadcastClient.cs index 7d666ce..1767d1a 100644 --- a/HyperbolicDownloaderApi/Networking/BroadcastClient.cs +++ b/HyperbolicDownloaderApi/Networking/BroadcastClient.cs @@ -26,7 +26,7 @@ internal class BroadcastClient if (ip4Address is null) { - ApiManager.SendMessageNewLine("Could not find suitable network adapter!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Could not find suitable network adapter!", NotificationMessageType.Error); return; } @@ -34,7 +34,7 @@ internal class BroadcastClient if (addressInformation is null) { - ApiManager.SendMessageNewLine("Could not find suitable network adapter!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Could not find suitable network adapter!", NotificationMessageType.Error); return; } diff --git a/HyperbolicDownloaderApi/Networking/HostsManager.cs b/HyperbolicDownloaderApi/Networking/HostsManager.cs index 763d764..389f9b1 100644 --- a/HyperbolicDownloaderApi/Networking/HostsManager.cs +++ b/HyperbolicDownloaderApi/Networking/HostsManager.cs @@ -53,7 +53,7 @@ public class HostsManager int activeHostsCount = 0; foreach (NetworkSocket host in hosts) { - ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning); + ApiManager.SendNotificationMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning); using TcpClient tcpClient = new TcpClient(); try @@ -62,7 +62,7 @@ public class HostsManager Console.CursorLeft = 0; if (tcpClient.Connected) { - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Active", NotificationMessageType.Success); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Active", NotificationMessageType.Success); host.LastActive = DateTime.Now; activeHostsCount++; } @@ -72,7 +72,7 @@ public class HostsManager { hostsToRemove.Add(host); } - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); } } catch @@ -82,7 +82,7 @@ public class HostsManager hostsToRemove.Add(host); } Console.CursorLeft = 0; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); } } From c2b84dd4754ee056ee47871913a5e00eb9d7aefe Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Fri, 22 Apr 2022 16:09:21 +0200 Subject: [PATCH 03/10] Code refactoring --- HyperbolicDownloader.sln | 10 ++-------- ...oaderCli.csproj => HyperbolicDownloader.csproj} | 0 HyperbolicDownloader/InputHandler.cs | 14 +++----------- HyperbolicDownloader/Program.cs | 10 +++++----- HyperbolicDownloaderApi/Networking/HostsManager.cs | 3 +-- 5 files changed, 11 insertions(+), 26 deletions(-) rename HyperbolicDownloader/{HyperbolicDownloaderCli.csproj => HyperbolicDownloader.csproj} (100%) diff --git a/HyperbolicDownloader.sln b/HyperbolicDownloader.sln index 6c5500c..bf1bc21 100644 --- a/HyperbolicDownloader.sln +++ b/HyperbolicDownloader.sln @@ -3,11 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloaderCli", "HyperbolicDownloader\HyperbolicDownloaderCli.csproj", "{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloader", "HyperbolicDownloader\HyperbolicDownloader.csproj", "{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloaderGUI", "HyperbolicDownloaderGUI\HyperbolicDownloaderGUI.csproj", "{E1CE6E07-F8A6-447F-837D-9D1943A42E96}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HyperbolicDownloaderApi", "HyperbolicDownloaderApi\HyperbolicDownloaderApi.csproj", "{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloaderApi", "HyperbolicDownloaderApi\HyperbolicDownloaderApi.csproj", "{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CA4F21C6-5B63-46C1-8576-91BB3FAE4FA7}" ProjectSection(SolutionItems) = preProject @@ -24,10 +22,6 @@ Global {7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}.Debug|Any CPU.Build.0 = Debug|Any CPU {7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}.Release|Any CPU.ActiveCfg = Release|Any CPU {7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}.Release|Any CPU.Build.0 = Release|Any CPU - {E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Release|Any CPU.Build.0 = Release|Any CPU {45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}.Debug|Any CPU.Build.0 = Debug|Any CPU {45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/HyperbolicDownloader/HyperbolicDownloaderCli.csproj b/HyperbolicDownloader/HyperbolicDownloader.csproj similarity index 100% rename from HyperbolicDownloader/HyperbolicDownloaderCli.csproj rename to HyperbolicDownloader/HyperbolicDownloader.csproj diff --git a/HyperbolicDownloader/InputHandler.cs b/HyperbolicDownloader/InputHandler.cs index d7ca1df..038ccb7 100644 --- a/HyperbolicDownloader/InputHandler.cs +++ b/HyperbolicDownloader/InputHandler.cs @@ -2,14 +2,14 @@ using HyperbolicDownloaderApi.Commands; using HyperbolicDownloaderApi.FileProcessing; +using HyperbolicDownloaderApi.Networking; using Stone_Red_Utilities.ConsoleExtentions; -namespace HyperbolicDownloaderApi; +namespace HyperbolicDownloader; internal class InputHandler { - private readonly HostsManager hostsManager; private readonly Commander commander = new Commander(); private bool exit = false; @@ -20,10 +20,8 @@ internal class InputHandler DownloadCommands downloadCommands = new DownloadCommands(hostsManager, filesManager); ClientCommands clientCommands = new ClientCommands(); - this.hostsManager = hostsManager; - commander.Register((_) => Console.Clear(), "clear", "cls"); - commander.Register(Exit, "exit", "quit"); + commander.Register((_) => exit = true, "exit", "quit"); commander.Register(clientCommands.ShowInfo, "info", "inf"); commander.Register(hostCommands.Discover, "discover", "disc"); @@ -72,10 +70,4 @@ internal class InputHandler } } } - - private void Exit(string _) - { - hostsManager.SaveHosts(); - exit = true; - } } \ No newline at end of file diff --git a/HyperbolicDownloader/Program.cs b/HyperbolicDownloader/Program.cs index 7c52a91..fb2199a 100644 --- a/HyperbolicDownloader/Program.cs +++ b/HyperbolicDownloader/Program.cs @@ -6,7 +6,7 @@ using Stone_Red_Utilities.ConsoleExtentions; using System.Text.Json; -namespace HyperbolicDownloaderApi; +namespace HyperbolicDownloader; internal static class Program { @@ -14,7 +14,7 @@ internal static class Program private static async Task Main(string[] args) { - Console.CancelKeyPress += Console_CancelKeyPress; + Console.CancelKeyPress += (_, _) => Close(); Console.CursorVisible = false; ApiManager.OnNotificationMessageRecived += ApiManager_OnNotificationMessageRecived; @@ -35,7 +35,7 @@ internal static class Program if (args.Length > 0 && File.Exists(args[0])) { - Commands.DownloadCommands downloadCommands = new Commands.DownloadCommands(apiManager.HostsManager, apiManager.FilesManager); + HyperbolicDownloaderApi.Commands.DownloadCommands downloadCommands = new HyperbolicDownloaderApi.Commands.DownloadCommands(apiManager.HostsManager, apiManager.FilesManager); downloadCommands.GetFileFrom(args[0]); Console.WriteLine("Do you want to continue using this instance? [y/N]"); if (char.ToLower(Console.ReadKey().KeyChar) != 'y') @@ -76,7 +76,7 @@ internal static class Program ConsoleExt.WriteLine("Ready", ConsoleColor.Green); inputHandler.ReadInput(); - ApiManager.ClosePorts(); + Close(); } private static void ApiManager_OnNotificationMessageRecived(object? sender, NotificationMessageEventArgs e) @@ -90,7 +90,7 @@ internal static class Program } } - private static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e) + private static void Close() { ApiManager.ClosePorts(); apiManager.HostsManager.SaveHosts(); diff --git a/HyperbolicDownloaderApi/Networking/HostsManager.cs b/HyperbolicDownloaderApi/Networking/HostsManager.cs index 389f9b1..7c61b1c 100644 --- a/HyperbolicDownloaderApi/Networking/HostsManager.cs +++ b/HyperbolicDownloaderApi/Networking/HostsManager.cs @@ -1,10 +1,9 @@ using HyperbolicDownloaderApi.Managment; -using HyperbolicDownloaderApi.Networking; using System.Net.Sockets; using System.Text.Json; -namespace HyperbolicDownloaderApi; +namespace HyperbolicDownloaderApi.Networking; public class HostsManager { From 826c6fc7eeac1df97846389737ef1a1d37dea9ff Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Mon, 25 Apr 2022 11:14:27 +0200 Subject: [PATCH 04/10] Fix command descriptions in `README.md` --- README.md | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index a6ace21..ac64040 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,6 @@ You can generate `.hyper` files with your client using the [generate](https://gi These files contain the hash value of the actual file and the hosts that should have the requested file. You can use the [get from](https://github.com/Stone-Red-Code/HyperbolicDownloader#getfrom) command to retrieve the file or if you are using Windows you can right-click the `.hyper` file, select `open with` and select the HyperbolicDownloader executable. - ## Disclaimer Keep in mind that all network traffic is not encrypted. So, do not send sensitive information with HyperbolicDownloader. @@ -41,31 +40,26 @@ Since none of the files are stored anywhere centralized, the quality of the file **Description:** Exits the application.\ **Parameter:** `none` - ### `clear` | `cls` **Description:** Clears the console.\ **Parameter:** `none` - ### `info` | `inf` **Description:** Displays the private and public IP address.\ **Parameter:** `none` - ### `discover` | `disc` **Description:** Tries to find other active hosts on the local network.\ **parameter:** `none` - ### `check` | `status` **Description:** Checks the status of known hosts.\ **parameter:** `none` - ### `list` | `ls` **Description:** Lists all files\ @@ -73,15 +67,14 @@ Since none of the files are stored anywhere centralized, the quality of the file #### ` files` -**Description:** Lists all files\ +**Description:** Lists all files.\ **parameter:** `none` #### ` hosts` -**description:** lists all hosts +**description:** Lists all hosts.\ **parameter:** `none` - ### `add` **Description:** Adds a file to the tracking list.\ @@ -97,7 +90,6 @@ Since none of the files are stored anywhere centralized, the quality of the file **Description:** Adds a host to the list of known hosts.\ **parameter:** `` - ### `remove` | `rm` **Description:** Removes a file from the tracking list.\ @@ -113,7 +105,6 @@ Since none of the files are stored anywhere centralized, the quality of the file **Description:** Removes a host from the list of known hosts.\ **parameter:** `` - ### `get` **Description:** Attempts to retrieve a file from another host using a hash.\ From f5dd85e38c6b601ba1acbb59e57e76865aa3dca7 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Mon, 25 Apr 2022 11:15:23 +0200 Subject: [PATCH 05/10] Update `Console.Commander.NET` to the newest version --- .../HyperbolicDownloader.csproj | 2 +- HyperbolicDownloader/InputHandler.cs | 39 ++++++++++--------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/HyperbolicDownloader/HyperbolicDownloader.csproj b/HyperbolicDownloader/HyperbolicDownloader.csproj index 101fc76..ec11e23 100644 --- a/HyperbolicDownloader/HyperbolicDownloader.csproj +++ b/HyperbolicDownloader/HyperbolicDownloader.csproj @@ -12,7 +12,7 @@ - + diff --git a/HyperbolicDownloader/InputHandler.cs b/HyperbolicDownloader/InputHandler.cs index 038ccb7..c18a2b8 100644 --- a/HyperbolicDownloader/InputHandler.cs +++ b/HyperbolicDownloader/InputHandler.cs @@ -20,30 +20,31 @@ internal class InputHandler DownloadCommands downloadCommands = new DownloadCommands(hostsManager, filesManager); ClientCommands clientCommands = new ClientCommands(); - commander.Register((_) => Console.Clear(), "clear", "cls"); - commander.Register((_) => exit = true, "exit", "quit"); - commander.Register(clientCommands.ShowInfo, "info", "inf"); - commander.Register(hostCommands.Discover, "discover", "disc"); + commander.Register(input => commander.PrintHelp(input), "help"); + commander.Register(_ => Console.Clear(), (HelpText)"Clears the console.", "clear", "cls"); + commander.Register(_ => exit = true, (HelpText)"Exits the application.", "exit", "quit"); + commander.Register(clientCommands.ShowInfo, (HelpText)"Displays the private and public IP address.", "info", "inf"); + commander.Register(hostCommands.Discover, (HelpText)"Tries to find other active hosts on the local network.", "discover", "disc"); - Command getCommand = commander.Register(downloadCommands.GetFile, "get"); - getCommand.Register(downloadCommands.GetFileFrom, "from"); + Command getCommand = commander.Register(downloadCommands.GetFile, (HelpText)"Attempts to retrieve a file from another host using a hash.", "get"); + getCommand.Register(downloadCommands.GetFileFrom, (HelpText)"Attempts to retrieve a file from another host using a .hyper file.", "from"); - Command generateCommad = commander.Register(fileCommands.GenerateFileFull, "generate", "gen"); - generateCommad.Register(fileCommands.GenerateFileSingle, "noscan"); + Command generateCommad = commander.Register(fileCommands.GenerateFileFull, (HelpText)"Generates a .hyper file from a file hash.", "generate", "gen"); + generateCommad.Register(fileCommands.GenerateFileSingle, (HelpText)"Generates a .hyper file from a file hash without checking the known hosts. This adds only the local host to the file.", "noscan"); - Command addCommand = commander.Register(fileCommands.AddFile, "add"); - addCommand.Register(hostCommands.AddHost, "host"); - addCommand.Register(fileCommands.AddFile, "file"); + Command addCommand = commander.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "add"); + addCommand.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "file"); + addCommand.Register(hostCommands.AddHost, (HelpText)"Adds a host to the list of known hosts.", "host"); - Command removeCommand = commander.Register(fileCommands.RemoveFile, "remove", "rm"); - removeCommand.Register(hostCommands.RemoveHost, "host"); - removeCommand.Register(fileCommands.RemoveFile, "file"); + Command removeCommand = commander.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "remove", "rm"); + removeCommand.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "file"); + removeCommand.Register(hostCommands.RemoveHost, (HelpText)"Removes a host from the list of known hosts.", "host"); - Command listCommand = commander.Register(fileCommands.ListFiles, "list", "ls"); - listCommand.Register(fileCommands.ListFiles, "files"); - listCommand.Register(hostCommands.ListHosts, "hosts"); + Command listCommand = commander.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "list", "ls"); + listCommand.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "files"); + listCommand.Register(hostCommands.ListHosts, (HelpText)"lists all hosts.", "hosts"); - commander.Register(hostCommands.CheckActiveHosts, "status", "check"); + commander.Register(hostCommands.CheckActiveHosts, (HelpText)"Checks the status of known hosts.", "status", "check"); } public void ReadInput() @@ -59,7 +60,7 @@ internal class InputHandler Console.CursorVisible = false; try { - if (!commander.Execute(input)) + if (!commander.Execute(input, out _)) { ConsoleExt.WriteLine("Unknown command!", ConsoleColor.Red); } From 4dd2b7274ea44869f9002f1feef31f68a3f20803 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Mon, 25 Apr 2022 11:16:01 +0200 Subject: [PATCH 06/10] Fix `StartTcpListener` method not stopping program if fails --- HyperbolicDownloader/Program.cs | 5 ++++- HyperbolicDownloaderApi/Managment/ApiManager.cs | 6 ++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/HyperbolicDownloader/Program.cs b/HyperbolicDownloader/Program.cs index fb2199a..d87fa39 100644 --- a/HyperbolicDownloader/Program.cs +++ b/HyperbolicDownloader/Program.cs @@ -52,7 +52,10 @@ internal static class Program ConsoleExt.WriteLine($"The private port is: {ApiConfiguration.PrivatePort}", ConsoleColor.Green); Console.WriteLine("Starting TCP listener..."); - apiManager.StartTcpListener(); + if (!apiManager.StartTcpListener()) + { + Console.ReadLine(); + } Console.WriteLine("Starting broadcast listener..."); apiManager.StartBroadcastListener(); diff --git a/HyperbolicDownloaderApi/Managment/ApiManager.cs b/HyperbolicDownloaderApi/Managment/ApiManager.cs index aeb485d..1d3f806 100644 --- a/HyperbolicDownloaderApi/Managment/ApiManager.cs +++ b/HyperbolicDownloaderApi/Managment/ApiManager.cs @@ -115,7 +115,7 @@ public class ApiManager broadcastClient.OnBroadcastRecived += BroadcastClient_OnBroadcastRecived; } - public void StartTcpListener() + public bool StartTcpListener() { try { @@ -128,8 +128,10 @@ public class ApiManager catch (SocketException ex) { SendNotificationMessageNewLine($"An error occurred while starting the TCP listener! Error message: {ex.Message}", NotificationMessageType.Error); // net stop hens && net start hns - Console.ReadKey(); + return false; } + + return true; } private async void BroadcastClient_OnBroadcastRecived(object? sender, BroadcastRecivedEventArgs recivedEventArgs) From 1f770ce13134ea4fcd89d8660f639dad12020135 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Thu, 28 Apr 2022 07:28:35 +0200 Subject: [PATCH 07/10] Add missing lines to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ac64040..dfc9950 100644 --- a/README.md +++ b/README.md @@ -111,12 +111,14 @@ Since none of the files are stored anywhere centralized, the quality of the file **parameter:** `` + #### ` from` **Description:** Attempts to retrieve a file from another host using a .hyper file.\ **Parameter:** `` + ### `generate` | `gen` **Description:** Generates a .hyper file from a file hash.\ From 7d662dc1134137baec8df4d93917dc450bbab9f6 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Fri, 25 Nov 2022 12:05:34 +0100 Subject: [PATCH 08/10] Ignore broadcast messages from own PC --- HyperbolicDownloaderApi/Managment/ApiManager.cs | 17 ++++++++++------- .../Networking/HostsManager.cs | 11 ++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/HyperbolicDownloaderApi/Managment/ApiManager.cs b/HyperbolicDownloaderApi/Managment/ApiManager.cs index 1d3f806..b79aa73 100644 --- a/HyperbolicDownloaderApi/Managment/ApiManager.cs +++ b/HyperbolicDownloaderApi/Managment/ApiManager.cs @@ -35,10 +35,10 @@ public class ApiManager if (device is not null) { - ipAddress = (device.GetExternalIPAsync()).GetAwaiter().GetResult()?.ToString(); + ipAddress = device.GetExternalIPAsync().GetAwaiter().GetResult()?.ToString(); } - if (ipAddress is null || ipAddress == "0.0.0.0") + if (ipAddress is null or "0.0.0.0") { ipAddress = NetworkUtilities.GetIP4Adress()?.ToString(); port = ApiConfiguration.PrivatePort; @@ -136,24 +136,27 @@ public class ApiManager private async void BroadcastClient_OnBroadcastRecived(object? sender, BroadcastRecivedEventArgs recivedEventArgs) { - Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {recivedEventArgs.IPEndPoint.Address}"); + IPAddress remoteIpAddress = recivedEventArgs.IPEndPoint.Address; + + Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {remoteIpAddress}"); List hostsToSend = HostsManager.ToList(); NetworkSocket? localSocket = GetLocalSocket(); - if (localSocket is null) + if (localSocket is null || remoteIpAddress.Equals(PublicIpAddress) || remoteIpAddress.Equals(NetworkUtilities.GetIP4Adress())) { + Debug.WriteLine("Invalid broadcast!"); return; } - hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IPEndPoint.Address.ToString()); + _ = hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IPEndPoint.Address.ToString()); hostsToSend.Add(localSocket); bool success = int.TryParse(recivedEventArgs.Message, out int remotePort); if (success) { - HostsManager.Add(new NetworkSocket(recivedEventArgs.IPEndPoint.Address.ToString(), remotePort, DateTime.Now)); + HostsManager.Add(new NetworkSocket(remoteIpAddress.ToString(), remotePort, DateTime.Now)); try { await NetworkClient.SendAsync(recivedEventArgs.IPEndPoint.Address, remotePort, "DiscoverAnswer", hostsToSend); @@ -182,7 +185,7 @@ public class ApiManager return; } - hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IpAddress.ToString()); + _ = hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IpAddress.ToString()); hostsToSend.Add(localSocket); if (recivedEventArgs.Data.Port != 0) diff --git a/HyperbolicDownloaderApi/Networking/HostsManager.cs b/HyperbolicDownloaderApi/Networking/HostsManager.cs index 7c61b1c..86eddcc 100644 --- a/HyperbolicDownloaderApi/Networking/HostsManager.cs +++ b/HyperbolicDownloaderApi/Networking/HostsManager.cs @@ -14,10 +14,7 @@ public class HostsManager { foreach (NetworkSocket host in hosts) { - if (!Contains(host)) - { - this.hosts.Add(host); - } + Add(host); } SaveHosts(); @@ -36,7 +33,7 @@ public class HostsManager { if (DateTime.Now - host.LastActive >= new TimeSpan(24, 0, 0) || forceRemove) { - hosts.RemoveAll(x => x.IPAddress == host.IPAddress && x.Port == host.Port); + _ = hosts.RemoveAll(x => x.IPAddress == host.IPAddress && x.Port == host.Port); } SaveHosts(); } @@ -57,7 +54,7 @@ public class HostsManager try { - tcpClient.ConnectAsync(host.IPAddress, host.Port).Wait(500); + _ = tcpClient.ConnectAsync(host.IPAddress, host.Port).Wait(500); Console.CursorLeft = 0; if (tcpClient.Connected) { @@ -87,7 +84,7 @@ public class HostsManager foreach (NetworkSocket host in hostsToRemove) { - hosts.Remove(host); + _ = hosts.Remove(host); } SaveHosts(); From fb21a9f4924b8f0d753022bd0e274a99efd9898e Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Mon, 6 Feb 2023 15:15:47 +0100 Subject: [PATCH 09/10] Code cleanup --- HyperbolicDownloader/InputHandler.cs | 28 +- HyperbolicDownloader/Program.cs | 13 +- .../Commands/DownloadCommands.cs | 2 +- .../Commands/FileCommands.cs | 4 +- .../Commands/HostCommands.cs | 4 +- .../Managment/ApiConfiguration.cs | 4 +- .../Networking/BroadcastClient.cs | 4 +- .../Networking/DataContainer.cs | 21 +- .../Networking/MessageRecivedEventArgs.cs | 41 +- .../Networking/NetworkClient.cs | 351 +++++++++--------- 10 files changed, 235 insertions(+), 237 deletions(-) diff --git a/HyperbolicDownloader/InputHandler.cs b/HyperbolicDownloader/InputHandler.cs index c18a2b8..3755c4f 100644 --- a/HyperbolicDownloader/InputHandler.cs +++ b/HyperbolicDownloader/InputHandler.cs @@ -20,31 +20,31 @@ internal class InputHandler DownloadCommands downloadCommands = new DownloadCommands(hostsManager, filesManager); ClientCommands clientCommands = new ClientCommands(); - commander.Register(input => commander.PrintHelp(input), "help"); - commander.Register(_ => Console.Clear(), (HelpText)"Clears the console.", "clear", "cls"); - commander.Register(_ => exit = true, (HelpText)"Exits the application.", "exit", "quit"); - commander.Register(clientCommands.ShowInfo, (HelpText)"Displays the private and public IP address.", "info", "inf"); - commander.Register(hostCommands.Discover, (HelpText)"Tries to find other active hosts on the local network.", "discover", "disc"); + _ = commander.Register(input => commander.PrintHelp(input), "help"); + _ = commander.Register(_ => Console.Clear(), (HelpText)"Clears the console.", "clear", "cls"); + _ = commander.Register(_ => exit = true, (HelpText)"Exits the application.", "exit", "quit"); + _ = commander.Register(clientCommands.ShowInfo, (HelpText)"Displays the private and public IP address.", "info", "inf"); + _ = commander.Register(hostCommands.Discover, (HelpText)"Tries to find other active hosts on the local network.", "discover", "disc"); Command getCommand = commander.Register(downloadCommands.GetFile, (HelpText)"Attempts to retrieve a file from another host using a hash.", "get"); - getCommand.Register(downloadCommands.GetFileFrom, (HelpText)"Attempts to retrieve a file from another host using a .hyper file.", "from"); + _ = getCommand.Register(downloadCommands.GetFileFrom, (HelpText)"Attempts to retrieve a file from another host using a .hyper file.", "from"); Command generateCommad = commander.Register(fileCommands.GenerateFileFull, (HelpText)"Generates a .hyper file from a file hash.", "generate", "gen"); - generateCommad.Register(fileCommands.GenerateFileSingle, (HelpText)"Generates a .hyper file from a file hash without checking the known hosts. This adds only the local host to the file.", "noscan"); + _ = generateCommad.Register(fileCommands.GenerateFileSingle, (HelpText)"Generates a .hyper file from a file hash without checking the known hosts. This adds only the local host to the file.", "noscan"); Command addCommand = commander.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "add"); - addCommand.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "file"); - addCommand.Register(hostCommands.AddHost, (HelpText)"Adds a host to the list of known hosts.", "host"); + _ = addCommand.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "file"); + _ = addCommand.Register(hostCommands.AddHost, (HelpText)"Adds a host to the list of known hosts.", "host"); Command removeCommand = commander.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "remove", "rm"); - removeCommand.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "file"); - removeCommand.Register(hostCommands.RemoveHost, (HelpText)"Removes a host from the list of known hosts.", "host"); + _ = removeCommand.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "file"); + _ = removeCommand.Register(hostCommands.RemoveHost, (HelpText)"Removes a host from the list of known hosts.", "host"); Command listCommand = commander.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "list", "ls"); - listCommand.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "files"); - listCommand.Register(hostCommands.ListHosts, (HelpText)"lists all hosts.", "hosts"); + _ = listCommand.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "files"); + _ = listCommand.Register(hostCommands.ListHosts, (HelpText)"lists all hosts.", "hosts"); - commander.Register(hostCommands.CheckActiveHosts, (HelpText)"Checks the status of known hosts.", "status", "check"); + _ = commander.Register(hostCommands.CheckActiveHosts, (HelpText)"Checks the status of known hosts.", "status", "check"); } public void ReadInput() diff --git a/HyperbolicDownloader/Program.cs b/HyperbolicDownloader/Program.cs index d87fa39..a6af901 100644 --- a/HyperbolicDownloader/Program.cs +++ b/HyperbolicDownloader/Program.cs @@ -45,6 +45,14 @@ internal static class Program Console.WriteLine(); } + await Initialize(); + + inputHandler.ReadInput(); + Close(); + } + + private static async Task Initialize() + { Console.WriteLine("Searching for a UPnP/NAT-PMP device..."); _ = await ApiManager.OpenPorts(); @@ -54,7 +62,7 @@ internal static class Program Console.WriteLine("Starting TCP listener..."); if (!apiManager.StartTcpListener()) { - Console.ReadLine(); + _ = Console.ReadLine(); } Console.WriteLine("Starting broadcast listener..."); @@ -77,9 +85,6 @@ internal static class Program Console.WriteLine($"{activeHostsCount} active host(s)."); ConsoleExt.WriteLine("Ready", ConsoleColor.Green); - - inputHandler.ReadInput(); - Close(); } private static void ApiManager_OnNotificationMessageRecived(object? sender, NotificationMessageEventArgs e) diff --git a/HyperbolicDownloaderApi/Commands/DownloadCommands.cs b/HyperbolicDownloaderApi/Commands/DownloadCommands.cs index 04ec861..574077b 100644 --- a/HyperbolicDownloaderApi/Commands/DownloadCommands.cs +++ b/HyperbolicDownloaderApi/Commands/DownloadCommands.cs @@ -152,7 +152,7 @@ public class DownloadCommands if (!Directory.Exists(directoryPath)) { - Directory.CreateDirectory(directoryPath); + _ = Directory.CreateDirectory(directoryPath); } using FileStream? fileStream = new FileStream(filePath, FileMode.Create); diff --git a/HyperbolicDownloaderApi/Commands/FileCommands.cs b/HyperbolicDownloaderApi/Commands/FileCommands.cs index 960daa5..e15fbf9 100644 --- a/HyperbolicDownloaderApi/Commands/FileCommands.cs +++ b/HyperbolicDownloaderApi/Commands/FileCommands.cs @@ -72,7 +72,7 @@ public class FileCommands string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles"); if (!Directory.Exists(directoryPath)) { - Directory.CreateDirectory(directoryPath); + _ = Directory.CreateDirectory(directoryPath); } hash = hash.Trim().ToLower(); @@ -111,7 +111,7 @@ public class FileCommands string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles"); if (!Directory.Exists(directoryPath)) { - Directory.CreateDirectory(directoryPath); + _ = Directory.CreateDirectory(directoryPath); } hash = hash.Trim().ToLower(); diff --git a/HyperbolicDownloaderApi/Commands/HostCommands.cs b/HyperbolicDownloaderApi/Commands/HostCommands.cs index 3e4ee1a..1bf31cd 100644 --- a/HyperbolicDownloaderApi/Commands/HostCommands.cs +++ b/HyperbolicDownloaderApi/Commands/HostCommands.cs @@ -72,7 +72,7 @@ public class HostCommands string portInput = parts[1]; _ = int.TryParse(portInput, out int port); - if (port < 1000 || port >= 6000) + if (port is < 1000 or >= 6000) { ApiManager.SendNotificationMessageNewLine("Invalid port number!", NotificationMessageType.Error); return; @@ -112,7 +112,7 @@ public class HostCommands _ = int.TryParse(portInput, out int port); - if (port < 1000 || port >= 6000) + if (port is < 1000 or >= 6000) { ApiManager.SendNotificationMessageNewLine("Invalid port number!", NotificationMessageType.Error); return; diff --git a/HyperbolicDownloaderApi/Managment/ApiConfiguration.cs b/HyperbolicDownloaderApi/Managment/ApiConfiguration.cs index 3dd3fd7..66a5cc6 100644 --- a/HyperbolicDownloaderApi/Managment/ApiConfiguration.cs +++ b/HyperbolicDownloaderApi/Managment/ApiConfiguration.cs @@ -1,6 +1,7 @@ using System.Reflection; namespace HyperbolicDownloaderApi.Managment; + public static class ApiConfiguration { public const int BroadcastPort = 2155; @@ -9,5 +10,4 @@ public static class ApiConfiguration public static string BasePath { get; } = Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location) ?? string.Empty; public static string HostsFilePath { get; } = Path.Combine(BasePath, "Hosts.json"); public static string FilesInfoPath { get; } = Path.Combine(BasePath, "Files.json"); - -} +} \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Networking/BroadcastClient.cs b/HyperbolicDownloaderApi/Networking/BroadcastClient.cs index 1767d1a..24684b8 100644 --- a/HyperbolicDownloaderApi/Networking/BroadcastClient.cs +++ b/HyperbolicDownloaderApi/Networking/BroadcastClient.cs @@ -43,7 +43,7 @@ internal class BroadcastClient byte[] sendbuf = Encoding.ASCII.GetBytes(message); IPEndPoint ep = new IPEndPoint(broadcast, port); - socket.SendTo(sendbuf, ep); + _ = socket.SendTo(sendbuf, ep); } public void StartListening(int port) @@ -58,7 +58,7 @@ internal class BroadcastClient udpListener = new UdpClient(port); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port); - Task.Run(() => + _ = Task.Run(() => { while (IsListening) { diff --git a/HyperbolicDownloaderApi/Networking/DataContainer.cs b/HyperbolicDownloaderApi/Networking/DataContainer.cs index 42ae3a3..42ef91f 100644 --- a/HyperbolicDownloaderApi/Networking/DataContainer.cs +++ b/HyperbolicDownloaderApi/Networking/DataContainer.cs @@ -1,14 +1,13 @@ -namespace HyperbolicDownloaderApi -{ - internal class DataContainer - { - public string EventName { get; set; } - public string JsonData { get; set; } +namespace HyperbolicDownloaderApi.Networking; - public DataContainer(string eventName, string jsonData) - { - JsonData = jsonData; - EventName = eventName; - } +internal class DataContainer +{ + public string EventName { get; set; } + public string JsonData { get; set; } + + public DataContainer(string eventName, string jsonData) + { + JsonData = jsonData; + EventName = eventName; } } \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Networking/MessageRecivedEventArgs.cs b/HyperbolicDownloaderApi/Networking/MessageRecivedEventArgs.cs index 217bac8..299bc5a 100644 --- a/HyperbolicDownloaderApi/Networking/MessageRecivedEventArgs.cs +++ b/HyperbolicDownloaderApi/Networking/MessageRecivedEventArgs.cs @@ -3,32 +3,31 @@ using System.Net.Sockets; using System.Text; using System.Text.Json; -namespace HyperbolicDownloaderApi +namespace HyperbolicDownloaderApi.Networking; + +internal class MessageRecivedEventArgs : EventArgs { - internal class MessageRecivedEventArgs : EventArgs + private readonly NetworkStream networkStream; + + public MessageRecivedEventArgs(NetworkStream networkStream, IPAddress ipAddress, T data) { - private readonly NetworkStream networkStream; + this.networkStream = networkStream; + Data = data; + IpAddress = ipAddress; + } - public MessageRecivedEventArgs(NetworkStream networkStream, IPAddress ipAddress, T data) - { - this.networkStream = networkStream; - Data = data; - IpAddress = ipAddress; - } + public T Data { get; set; } - public T Data { get; set; } + public IPAddress IpAddress { get; set; } - public IPAddress IpAddress { get; set; } + public async Task SendResponseAsync(object response) + { + byte[] bytesToSend = Encoding.ASCII.GetBytes(JsonSerializer.Serialize(response)); + await networkStream.WriteAsync(bytesToSend); + } - public async Task SendResponseAsync(object response) - { - byte[] bytesToSend = Encoding.ASCII.GetBytes(JsonSerializer.Serialize(response)); - await networkStream.WriteAsync(bytesToSend); - } - - public void SendResponse(object response) - { - SendResponseAsync(response).GetAwaiter().GetResult(); - } + public void SendResponse(object response) + { + SendResponseAsync(response).GetAwaiter().GetResult(); } } \ No newline at end of file diff --git a/HyperbolicDownloaderApi/Networking/NetworkClient.cs b/HyperbolicDownloaderApi/Networking/NetworkClient.cs index 00f7236..18c44c9 100644 --- a/HyperbolicDownloaderApi/Networking/NetworkClient.cs +++ b/HyperbolicDownloaderApi/Networking/NetworkClient.cs @@ -6,205 +6,200 @@ using System.Net.Sockets; using System.Text; using System.Text.Json; -namespace HyperbolicDownloaderApi.Networking +namespace HyperbolicDownloaderApi.Networking; + +internal class NetworkClient { - internal class NetworkClient + public bool IsListening { get; private set; } = false; + + private TcpListener? tcpListener; + private readonly FilesManager filesManager; + private readonly Dictionary events = new(); + + public NetworkClient(FilesManager filesManager) { - public bool IsListening { get; private set; } = false; + this.filesManager = filesManager; + } - private TcpListener? tcpListener; - private readonly FilesManager filesManager; - private readonly Dictionary events = new(); - - public NetworkClient(FilesManager filesManager) + public static async Task SendAsync(IPAddress remoteIp, int remotePort, string eventName, object data) + { + if (remoteIp is null) { - this.filesManager = filesManager; + throw new ArgumentNullException(nameof(remoteIp)); } - public static async Task SendAsync(IPAddress remoteIp, int remotePort, string eventName, object data) + TcpClient client = new TcpClient(); + + await client.ConnectAsync(remoteIp, remotePort); + + NetworkStream nwStream = client.GetStream(); + + string stringData = JsonSerializer.Serialize(new DataContainer(eventName, JsonSerializer.Serialize(data))); + byte[] bytesToSend = Encoding.ASCII.GetBytes(stringData); + + await nwStream.WriteAsync(bytesToSend); + + byte[] bytesToRead = new byte[client.ReceiveBufferSize]; + int bytesRead = await nwStream.ReadAsync(bytesToRead.AsMemory(0, client.ReceiveBufferSize)); + string response = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead); + + client.Close(); + + if (string.IsNullOrWhiteSpace(response)) { - if (remoteIp is null) + return default; + } + else + { + return JsonSerializer.Deserialize(response); + } + } + + public static async Task SendAsync(IPAddress remoteIp, int remotePort, string eventName, object data) + { + if (remoteIp is null) + { + throw new ArgumentNullException(nameof(remoteIp)); + } + + TcpClient client = new TcpClient(); + + await client.ConnectAsync(remoteIp, remotePort); + + NetworkStream nwStream = client.GetStream(); + + string stringData = JsonSerializer.Serialize(new DataContainer(eventName, JsonSerializer.Serialize(data))); + byte[] bytesToSend = Encoding.ASCII.GetBytes(stringData); + + await nwStream.WriteAsync(bytesToSend); + + client.Close(); + } + + public static T? Send(IPAddress remoteIp, int remotePort, string eventName, object data) + { + return SendAsync(remoteIp, remotePort, eventName, data).GetAwaiter().GetResult(); + } + + public static void Send(IPAddress remoteIp, int remotePort, string eventName, object data) + { + SendAsync(remoteIp, remotePort, eventName, data).GetAwaiter().GetResult(); + } + + public void StartListening(int port) + { + if (IsListening) + { + throw new InvalidOperationException("Already listening!"); + } + + tcpListener = new TcpListener(IPAddress.Any, port); + + tcpListener.Start(); + IsListening = true; + + _ = Task.Run(async () => + { + while (IsListening) { - throw new ArgumentNullException(nameof(remoteIp)); + try + { + TcpClient client = tcpListener.AcceptTcpClient(); + NetworkStream nwStream = client.GetStream(); + byte[] buffer = new byte[client.ReceiveBufferSize]; + + int bytesRead = await nwStream.ReadAsync(buffer.AsMemory(0, client.ReceiveBufferSize)); + + string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); + + if (dataReceived.StartsWith("Download")) + { + _ = Upload(client, dataReceived[8..]); + continue; + } + if (string.IsNullOrWhiteSpace(dataReceived)) + { + client.Close(); + continue; + } + + DataContainer? dataContainer = JsonSerializer.Deserialize(dataReceived); + + if (dataContainer is not null && events.ContainsKey(dataContainer.EventName)) + { + (Type type, Delegate method) = events[dataContainer.EventName]; + + Type eventArgsType = typeof(MessageRecivedEventArgs<>).MakeGenericType(type); + + object? eventArgs = Activator.CreateInstance( + eventArgsType, + nwStream, + (client.Client.RemoteEndPoint as IPEndPoint)?.Address, + JsonSerializer.Deserialize(dataContainer.JsonData, type)); + + _ = (method?.DynamicInvoke(this, eventArgs)); + } + + client.Close(); + } + catch (SocketException ex) + { + if (ex.SocketErrorCode != SocketError.Interrupted) + { + throw; + } + } } + tcpListener.Stop(); + }); + } - TcpClient client = new TcpClient(); - - await client.ConnectAsync(remoteIp, remotePort); - + private async Task Upload(TcpClient client, string hash) + { + try + { + byte[] bytesToSend; + hash = hash.Trim(); NetworkStream nwStream = client.GetStream(); - - string stringData = JsonSerializer.Serialize(new DataContainer(eventName, JsonSerializer.Serialize(data))); - byte[] bytesToSend = Encoding.ASCII.GetBytes(stringData); - - await nwStream.WriteAsync(bytesToSend); - - byte[] bytesToRead = new byte[client.ReceiveBufferSize]; - int bytesRead = await nwStream.ReadAsync(bytesToRead.AsMemory(0, client.ReceiveBufferSize)); - string response = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead); - - client.Close(); - - if (string.IsNullOrWhiteSpace(response)) + client.SendBufferSize = 64000; + if (filesManager.TryGet(hash, out PrivateHyperFileInfo? hyperFileInfo) && File.Exists(hyperFileInfo?.FilePath)) { - return default; + FileInfo fileInfo = new FileInfo(hyperFileInfo.FilePath); + + bytesToSend = Encoding.ASCII.GetBytes($"{fileInfo.Length}/{Path.GetFileName(hyperFileInfo.FilePath)}"); + + Array.Resize(ref bytesToSend, 1000); + + await nwStream.WriteAsync(bytesToSend); + foreach (byte[]? chunk in FileCompressor.ReadChunks(hyperFileInfo.FilePath, 64000).Where(chunk => chunk is not null)) + { + await nwStream.WriteAsync(chunk); + } } else { - return JsonSerializer.Deserialize(response); + bytesToSend = Encoding.ASCII.GetBytes("File not found!"); + await nwStream.WriteAsync(bytesToSend); } } - - public static async Task SendAsync(IPAddress remoteIp, int remotePort, string eventName, object data) + catch (Exception ex) + { + Debug.WriteLine(ex); + } + finally { - if (remoteIp is null) - { - throw new ArgumentNullException(nameof(remoteIp)); - } - - TcpClient client = new TcpClient(); - - await client.ConnectAsync(remoteIp, remotePort); - - NetworkStream nwStream = client.GetStream(); - - string stringData = JsonSerializer.Serialize(new DataContainer(eventName, JsonSerializer.Serialize(data))); - byte[] bytesToSend = Encoding.ASCII.GetBytes(stringData); - - await nwStream.WriteAsync(bytesToSend); - client.Close(); } + } - public static T? Send(IPAddress remoteIp, int remotePort, string eventName, object data) - { - return SendAsync(remoteIp, remotePort, eventName, data).GetAwaiter().GetResult(); - } + public void StopListening() + { + tcpListener?.Stop(); + IsListening = false; + } - public static void Send(IPAddress remoteIp, int remotePort, string eventName, object data) - { - SendAsync(remoteIp, remotePort, eventName, data).GetAwaiter().GetResult(); - } - - public void StartListening(int port) - { - if (IsListening) - { - throw new InvalidOperationException("Already listening!"); - } - - tcpListener = new TcpListener(IPAddress.Any, port); - - tcpListener.Start(); - IsListening = true; - - Task.Run(async () => - { - while (IsListening) - { - try - { - TcpClient client = tcpListener.AcceptTcpClient(); - NetworkStream nwStream = client.GetStream(); - byte[] buffer = new byte[client.ReceiveBufferSize]; - - int bytesRead = await nwStream.ReadAsync(buffer.AsMemory(0, client.ReceiveBufferSize)); - - string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); - - if (dataReceived.StartsWith("Download")) - { - _ = Upload(client, dataReceived[8..]); - continue; - } - if (string.IsNullOrWhiteSpace(dataReceived)) - { - client.Close(); - continue; - } - - DataContainer? dataContainer = JsonSerializer.Deserialize(dataReceived); - - if (dataContainer is not null && events.ContainsKey(dataContainer.EventName)) - { - (Type type, Delegate method) = events[dataContainer.EventName]; - - Type eventArgsType = typeof(MessageRecivedEventArgs<>).MakeGenericType(type); - - object? eventArgs = Activator.CreateInstance( - eventArgsType, - nwStream, - (client.Client.RemoteEndPoint as IPEndPoint)?.Address, - JsonSerializer.Deserialize(dataContainer.JsonData, type)); - - method?.DynamicInvoke(this, eventArgs); - } - - client.Close(); - } - catch (SocketException ex) - { - if (ex.SocketErrorCode != SocketError.Interrupted) - { - throw; - } - } - } - tcpListener.Stop(); - }); - } - - private async Task Upload(TcpClient client, string hash) - { - try - { - byte[] bytesToSend; - hash = hash.Trim(); - NetworkStream nwStream = client.GetStream(); - client.SendBufferSize = 64000; - if (filesManager.TryGet(hash, out PrivateHyperFileInfo? hyperFileInfo) && File.Exists(hyperFileInfo?.FilePath)) - { - FileInfo fileInfo = new FileInfo(hyperFileInfo.FilePath); - - bytesToSend = Encoding.ASCII.GetBytes($"{fileInfo.Length}/{Path.GetFileName(hyperFileInfo.FilePath)}"); - - Array.Resize(ref bytesToSend, 1000); - - await nwStream.WriteAsync(bytesToSend); - - foreach (byte[]? chunk in FileCompressor.ReadChunks(hyperFileInfo.FilePath, 64000)) - { - if (chunk is not null) - { - await nwStream.WriteAsync(chunk); - } - } - } - else - { - bytesToSend = Encoding.ASCII.GetBytes("File not found!"); - await nwStream.WriteAsync(bytesToSend); - } - } - catch (Exception ex) - { - Debug.WriteLine(ex); - } - finally - { - client.Close(); - } - } - - public void StopListening() - { - tcpListener?.Stop(); - IsListening = false; - } - - public void ListenTo(string eventName, EventHandler> eventHandler) - { - events.Add(eventName, (typeof(T), eventHandler)); - } + public void ListenTo(string eventName, EventHandler> eventHandler) + { + events.Add(eventName, (typeof(T), eventHandler)); } } \ No newline at end of file From 6f9626fcfd85b6eb91efe9a74b41226fece41d4a Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Mon, 6 Feb 2023 15:28:04 +0100 Subject: [PATCH 10/10] Add response to `discover` command. --- HyperbolicDownloaderApi/Commands/HostCommands.cs | 5 +++++ HyperbolicDownloaderApi/Managment/ApiManager.cs | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/HyperbolicDownloaderApi/Commands/HostCommands.cs b/HyperbolicDownloaderApi/Commands/HostCommands.cs index 1bf31cd..1ed4ac6 100644 --- a/HyperbolicDownloaderApi/Commands/HostCommands.cs +++ b/HyperbolicDownloaderApi/Commands/HostCommands.cs @@ -19,8 +19,13 @@ public class HostCommands public void Discover(string _) { ApiManager.SendNotificationMessageNewLine("Running local discovery routine...", NotificationMessageType.Info); + + int hostsCountBefore = hostsManager.Count; + BroadcastClient.Send(ApiConfiguration.BroadcastPort, ApiConfiguration.PrivatePort.ToString()); Thread.Sleep(3000); + + ApiManager.SendNotificationMessageNewLine($"Found {hostsManager.Count - hostsCountBefore} host(s)", NotificationMessageType.Info); } public void CheckActiveHosts(string _) diff --git a/HyperbolicDownloaderApi/Managment/ApiManager.cs b/HyperbolicDownloaderApi/Managment/ApiManager.cs index b79aa73..94e697e 100644 --- a/HyperbolicDownloaderApi/Managment/ApiManager.cs +++ b/HyperbolicDownloaderApi/Managment/ApiManager.cs @@ -149,7 +149,7 @@ public class ApiManager return; } - _ = hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IPEndPoint.Address.ToString()); + _ = hostsToSend.RemoveAll(x => x.IPAddress == remoteIpAddress.ToString()); hostsToSend.Add(localSocket); bool success = int.TryParse(recivedEventArgs.Message, out int remotePort);