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] 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