Skip to content

Commit

Permalink
Merge pull request #2 from Stone-Red-Code/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Stone-Red-Code authored Feb 6, 2023
2 parents 9f08b5c + 2003cdc commit f7aaa40
Show file tree
Hide file tree
Showing 15 changed files with 243 additions and 256 deletions.
10 changes: 2 additions & 8 deletions HyperbolicDownloader.sln
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Console.Commander.NET" Version="1.0.0" />
<PackageReference Include="Console.Commander.NET" Version="1.0.1" />
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" />
</ItemGroup>

Expand Down
51 changes: 22 additions & 29 deletions HyperbolicDownloader/InputHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -20,32 +20,31 @@ public InputHandler(HostsManager hostsManager, FilesManager filesManager)
DownloadCommands downloadCommands = new DownloadCommands(hostsManager, filesManager);
ClientCommands clientCommands = new ClientCommands();

this.hostsManager = hostsManager;
_ = 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((_) => Console.Clear(), "clear", "cls");
commander.Register(Exit, "exit", "quit");
commander.Register(clientCommands.ShowInfo, "info", "inf");
commander.Register(hostCommands.Discover, "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");

Command getCommand = commander.Register(downloadCommands.GetFile, "get");
getCommand.Register(downloadCommands.GetFileFrom, "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");

Command generateCommad = commander.Register(fileCommands.GenerateFileFull, "generate", "gen");
generateCommad.Register(fileCommands.GenerateFileSingle, "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");

Command addCommand = commander.Register(fileCommands.AddFile, "add");
addCommand.Register(hostCommands.AddHost, "host");
addCommand.Register(fileCommands.AddFile, "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 removeCommand = commander.Register(fileCommands.RemoveFile, "remove", "rm");
removeCommand.Register(hostCommands.RemoveHost, "host");
removeCommand.Register(fileCommands.RemoveFile, "file");
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");

Command listCommand = commander.Register(fileCommands.ListFiles, "list", "ls");
listCommand.Register(fileCommands.ListFiles, "files");
listCommand.Register(hostCommands.ListHosts, "hosts");

commander.Register(hostCommands.CheckActiveHosts, "status", "check");
_ = commander.Register(hostCommands.CheckActiveHosts, (HelpText)"Checks the status of known hosts.", "status", "check");
}

public void ReadInput()
Expand All @@ -61,7 +60,7 @@ public void ReadInput()
Console.CursorVisible = false;
try
{
if (!commander.Execute(input))
if (!commander.Execute(input, out _))
{
ConsoleExt.WriteLine("Unknown command!", ConsoleColor.Red);
}
Expand All @@ -72,10 +71,4 @@ public void ReadInput()
}
}
}

private void Exit(string _)
{
hostsManager.SaveHosts();
exit = true;
}
}
24 changes: 16 additions & 8 deletions HyperbolicDownloader/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@

using System.Text.Json;

namespace HyperbolicDownloaderApi;
namespace HyperbolicDownloader;

internal static class Program
{
private static readonly ApiManager apiManager = new ApiManager();

private static async Task Main(string[] args)
{
Console.CancelKeyPress += Console_CancelKeyPress;
Console.CancelKeyPress += (_, _) => Close();
Console.CursorVisible = false;

ApiManager.OnNotificationMessageRecived += ApiManager_OnNotificationMessageRecived;
Expand All @@ -35,7 +35,7 @@ private static async Task Main(string[] args)

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')
Expand All @@ -45,14 +45,25 @@ private static async Task Main(string[] args)
Console.WriteLine();
}

await Initialize();

inputHandler.ReadInput();
Close();
}

private static async Task Initialize()
{
Console.WriteLine("Searching for a UPnP/NAT-PMP device...");
_ = await ApiManager.OpenPorts();

ConsoleExt.WriteLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()} ", ConsoleColor.Green);
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();
Expand All @@ -74,9 +85,6 @@ private static async Task Main(string[] args)
Console.WriteLine($"{activeHostsCount} active host(s).");

ConsoleExt.WriteLine("Ready", ConsoleColor.Green);

inputHandler.ReadInput();
ApiManager.ClosePorts();
}

private static void ApiManager_OnNotificationMessageRecived(object? sender, NotificationMessageEventArgs e)
Expand All @@ -90,7 +98,7 @@ private static void ApiManager_OnNotificationMessageRecived(object? sender, Noti
}
}

private static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
private static void Close()
{
ApiManager.ClosePorts();
apiManager.HostsManager.SaveHosts();
Expand Down
2 changes: 1 addition & 1 deletion HyperbolicDownloaderApi/Commands/DownloadCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public void GetFile(string hash)

if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
_ = Directory.CreateDirectory(directoryPath);
}

using FileStream? fileStream = new FileStream(filePath, FileMode.Create);
Expand Down
4 changes: 2 additions & 2 deletions HyperbolicDownloaderApi/Commands/FileCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void GenerateFileSingle(string hash)
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
_ = Directory.CreateDirectory(directoryPath);
}

hash = hash.Trim().ToLower();
Expand Down Expand Up @@ -111,7 +111,7 @@ public void GenerateFileFull(string hash)
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
_ = Directory.CreateDirectory(directoryPath);
}

hash = hash.Trim().ToLower();
Expand Down
9 changes: 7 additions & 2 deletions HyperbolicDownloaderApi/Commands/HostCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,13 @@ public HostCommands(HostsManager hostsManager)
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 _)
Expand Down Expand Up @@ -72,7 +77,7 @@ public void RemoveHost(string args)
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;
Expand Down Expand Up @@ -112,7 +117,7 @@ public void AddHost(string args)

_ = 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;
Expand Down
4 changes: 2 additions & 2 deletions HyperbolicDownloaderApi/Managment/ApiConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Reflection;

namespace HyperbolicDownloaderApi.Managment;

public static class ApiConfiguration
{
public const int BroadcastPort = 2155;
Expand All @@ -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");

}
}
23 changes: 14 additions & 9 deletions HyperbolicDownloaderApi/Managment/ApiManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ public 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;
Expand Down Expand Up @@ -115,7 +115,7 @@ public void StartBroadcastListener()
broadcastClient.OnBroadcastRecived += BroadcastClient_OnBroadcastRecived;
}

public void StartTcpListener()
public bool StartTcpListener()
{
try
{
Expand All @@ -128,30 +128,35 @@ public void StartTcpListener()
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)
{
Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {recivedEventArgs.IPEndPoint.Address}");
IPAddress remoteIpAddress = recivedEventArgs.IPEndPoint.Address;

Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {remoteIpAddress}");
List<NetworkSocket> 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 == remoteIpAddress.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);
Expand Down Expand Up @@ -180,7 +185,7 @@ private async void GetHostList(object? sender, MessageRecivedEventArgs<NetworkSo
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)
Expand Down
4 changes: 2 additions & 2 deletions HyperbolicDownloaderApi/Networking/BroadcastClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static void Send(int port, string message)
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)
Expand All @@ -58,7 +58,7 @@ public void StartListening(int port)
udpListener = new UdpClient(port);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);

Task.Run(() =>
_ = Task.Run(() =>
{
while (IsListening)
{
Expand Down
19 changes: 9 additions & 10 deletions HyperbolicDownloaderApi/Networking/DataContainer.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
namespace HyperbolicDownloaderApi
namespace HyperbolicDownloaderApi.Networking;

internal class DataContainer
{
internal class DataContainer
{
public string EventName { get; set; }
public string JsonData { get; set; }
public string EventName { get; set; }
public string JsonData { get; set; }

public DataContainer(string eventName, string jsonData)
{
JsonData = jsonData;
EventName = eventName;
}
public DataContainer(string eventName, string jsonData)
{
JsonData = jsonData;
EventName = eventName;
}
}
Loading

0 comments on commit f7aaa40

Please sign in to comment.