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 diff --git a/HyperbolicDownloader/HyperbolicDownloaderCli.csproj b/HyperbolicDownloader/HyperbolicDownloaderCli.csproj index 1a90c33..101fc76 100644 --- a/HyperbolicDownloader/HyperbolicDownloaderCli.csproj +++ b/HyperbolicDownloader/HyperbolicDownloaderCli.csproj @@ -1,4 +1,4 @@ - + Exe 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 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 void ShowInfo(string _) { 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 15d623f..04ec861 100644 --- a/HyperbolicDownloaderApi/Commands/DownloadCommands.cs +++ b/HyperbolicDownloaderApi/Commands/DownloadCommands.cs @@ -27,7 +27,7 @@ public void GetFileFrom(string path) { if (string.IsNullOrWhiteSpace(path)) { - ApiManager.SendMessageNewLine("Path is empty!", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Path is empty!", NotificationMessageType.Error); return; } @@ -35,7 +35,7 @@ public void GetFileFrom(string path) 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 void GetFileFrom(string path) 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 void GetFile(string hash) { 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 void GetFile(string hash) 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 void GetFile(string hash) 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 void GetFile(string hash) 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); @@ -114,12 +114,12 @@ public void GetFile(string hash) int bytesRead; try { - bytesRead = nwStream.Read(buffer, 0, tcpClient.ReceiveBufferSize); + bytesRead = nwStream.Read(buffer, 0, 1000); } 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; } @@ -127,109 +127,110 @@ public void GetFile(string hash) string[] parts = dataReceived.Split('/'); - if (parts.Length == 2) //If received data does not contain 2 parts -> error + if (parts.Length != 2) //If received data does not contain 2 parts -> error { - bool validFileSize = int.TryParse(parts[0], out int fileSize); + ApiManager.SendNotificationMessageNewLine(dataReceived, NotificationMessageType.Error); + continue; + } - if (!validFileSize || fileSize <= 0) - { - ApiManager.SendMessageNewLine("Invalid file size!", NotificationMessageType.Error); - continue; - } + bool validFileSize = int.TryParse(parts[0], out int fileSize); - string fileName = parts[1].ToFileName(); - string directoryPath = Path.Combine(ApiConfiguration.BasePath, "Downloads"); - string filePath = Path.Combine(directoryPath, fileName); + if (!validFileSize || fileSize <= 0) + { + ApiManager.SendNotificationMessageNewLine("Invalid file size!", NotificationMessageType.Error); + continue; + } - ApiManager.SendMessageNewLine($"File name: {fileName}"); - ApiManager.SendMessageNewLine($"Starting download..."); + string fileName = parts[1].ToFileName(); + string directoryPath = Path.Combine(ApiConfiguration.BasePath, "Downloads"); + string filePath = Path.Combine(directoryPath, fileName); - int totalBytesRead = 0; + ApiManager.SendNotificationMessageNewLine($"File name: {fileName}"); + ApiManager.SendNotificationMessageNewLine($"Starting download..."); - if (!Directory.Exists(directoryPath)) - { - Directory.CreateDirectory(directoryPath); - } + int totalBytesRead = 0; - using FileStream? fileStream = new FileStream(filePath, FileMode.Create); + if (!Directory.Exists(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + + using FileStream? fileStream = new FileStream(filePath, FileMode.Create); - int bytesInOneSecond = 0; - int unitsPerSecond = 0; - string unit = "Kb"; + int bytesInOneSecond = 0; + int unitsPerSecond = 0; + string unit = "Kb"; - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); - while (totalBytesRead < fileSize) + Stopwatch stopWatch = new Stopwatch(); + stopWatch.Start(); + while (totalBytesRead < fileSize) + { + try { - try - { - bytesRead = nwStream.Read(reciveBuffer, 0, reciveBuffer.Length); - } - catch (IOException) - { - ApiManager.SendMessageNewLine(string.Empty); - ApiManager.SendMessageNewLine("Lost connection to other host!", NotificationMessageType.Error); - break; - } + bytesRead = nwStream.Read(reciveBuffer, 0, reciveBuffer.Length); + } + catch (IOException ex) + { + Debug.WriteLine(ex); + ApiManager.SendNotificationMessageNewLine(string.Empty); + ApiManager.SendNotificationMessageNewLine("Lost connection to other host!", NotificationMessageType.Error); + break; + } - bytesRead = Math.Min(bytesRead, fileSize - totalBytesRead); + bytesRead = Math.Min(bytesRead, fileSize - totalBytesRead); - fileStream.Write(reciveBuffer, 0, bytesRead); - totalBytesRead += bytesRead; + fileStream.Write(reciveBuffer, 0, bytesRead); + totalBytesRead += bytesRead; - bytesInOneSecond += bytesRead; + bytesInOneSecond += bytesRead; - if (stopWatch.ElapsedMilliseconds >= 1000) + if (stopWatch.Elapsed.TotalSeconds >= 1) + { + unitsPerSecond = (int)(bytesInOneSecond * stopWatch.Elapsed.TotalSeconds); + if (unitsPerSecond > 125000) { - unitsPerSecond = (unitsPerSecond + bytesInOneSecond) / 2; - if (unitsPerSecond > 125000) - { - unitsPerSecond /= 125000; - unit = "Mb"; - } - else - { - unitsPerSecond /= 125; - unit = "Kb"; - } - bytesInOneSecond = 0; - stopWatch.Restart(); + unitsPerSecond /= 125000; + unit = "Mb"; } - - ApiManager.SendMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] "); + else + { + unitsPerSecond /= 125; + unit = "Kb"; + } + bytesInOneSecond = 0; + stopWatch.Restart(); } - fileStream.Close(); + ApiManager.SendNotificationMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] "); + } - if (totalBytesRead < fileSize) - { - continue; - } + fileStream.Close(); - ApiManager.SendMessageNewLine(string.Empty); + if (totalBytesRead < fileSize) + { + continue; + } - ApiManager.SendMessageNewLine("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(string.Empty); - ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}"); - ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success); - stopWatch.Stop(); - hostsManager.SaveHosts(); - return; + ApiManager.SendNotificationMessageNewLine("Validating file..."); + if (FileValidator.ValidateHash(filePath, hash)) + { + _ = filesManager.TryAdd(filePath, out _, out _); } else { - ApiManager.SendMessageNewLine(dataReceived, NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine("Warning: File hash does not match! File might me corrupted or manipulated! Trying next host...", NotificationMessageType.Warning); + continue; } + + 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 8586f7a..960daa5 100644 --- a/HyperbolicDownloaderApi/Commands/FileCommands.cs +++ b/HyperbolicDownloaderApi/Commands/FileCommands.cs @@ -23,12 +23,12 @@ public void AddFile(string path) { 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 void RemoveFile(string hash) 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 void ListFiles(string _) 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 void GenerateFileSingle(string hash) 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 void GenerateFileSingle(string hash) 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 void GenerateFileSingle(string hash) 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 void GenerateFileFull(string hash) 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 void GenerateFileFull(string hash) 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 void GenerateFileFull(string hash) 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 void GenerateFileFull(string hash) 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 void GenerateFileFull(string hash) 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 void GenerateFileFull(string hash) 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 796acba..3e4ee1a 100644 --- a/HyperbolicDownloaderApi/Commands/HostCommands.cs +++ b/HyperbolicDownloaderApi/Commands/HostCommands.cs @@ -18,7 +18,7 @@ public HostCommands(HostsManager hostsManager) 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 void CheckActiveHosts(string _) 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 void ListHosts(string _) 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 void RemoveHost(string args) 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 void RemoveHost(string args) _ = 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 void RemoveHost(string args) 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,18 +102,19 @@ public void AddHost(string args) 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; } string ipAddressInput = parts[0]; string portInput = parts[1]; - IPAddress? ipAddress = null; + IPAddress? ipAddress; _ = 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; } else if (!IPAddress.TryParse(ipAddressInput, out ipAddress)) @@ -130,33 +131,33 @@ public void AddHost(string args) 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 static async Task OpenPorts() 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 static void ClosePorts() } 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 void StartTcpListener() } 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 @@ private async void BroadcastClient_OnBroadcastRecived(object? sender, BroadcastR 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 @@ private async void HasFile(object? sender, MessageRecivedEventArgs reciv 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 @@ public static void Send(int port, string message) 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 @@ public static void Send(int port, string message) 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 60f18c4..389f9b1 100644 --- a/HyperbolicDownloaderApi/Networking/HostsManager.cs +++ b/HyperbolicDownloaderApi/Networking/HostsManager.cs @@ -53,16 +53,16 @@ public int CheckHostsActivity() 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 { - tcpClient.ConnectAsync(host.IPAddress, host.Port).Wait(1000); + tcpClient.ConnectAsync(host.IPAddress, host.Port).Wait(500); 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 int CheckHostsActivity() { 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 int CheckHostsActivity() hostsToRemove.Add(host); } Console.CursorLeft = 0; - ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); + ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error); } } diff --git a/HyperbolicDownloaderApi/Networking/NetworkClient.cs b/HyperbolicDownloaderApi/Networking/NetworkClient.cs index 95fa50d..00f7236 100644 --- a/HyperbolicDownloaderApi/Networking/NetworkClient.cs +++ b/HyperbolicDownloaderApi/Networking/NetworkClient.cs @@ -167,6 +167,9 @@ private async Task Upload(TcpClient client, string hash) 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)) @@ -182,12 +185,15 @@ private async Task Upload(TcpClient client, string hash) bytesToSend = Encoding.ASCII.GetBytes("File not found!"); await nwStream.WriteAsync(bytesToSend); } - client.Close(); } catch (Exception ex) { Debug.WriteLine(ex); } + finally + { + client.Close(); + } } public void StopListening()