Skip to content

Commit f7aaa40

Browse files
Merge pull request #2 from Stone-Red-Code/develop
Develop
2 parents 9f08b5c + 2003cdc commit f7aaa40

File tree

15 files changed

+243
-256
lines changed

15 files changed

+243
-256
lines changed

HyperbolicDownloader.sln

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio Version 17
44
VisualStudioVersion = 17.0.32112.339
55
MinimumVisualStudioVersion = 10.0.40219.1
6-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloaderCli", "HyperbolicDownloader\HyperbolicDownloaderCli.csproj", "{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}"
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloader", "HyperbolicDownloader\HyperbolicDownloader.csproj", "{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}"
77
EndProject
8-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloaderGUI", "HyperbolicDownloaderGUI\HyperbolicDownloaderGUI.csproj", "{E1CE6E07-F8A6-447F-837D-9D1943A42E96}"
9-
EndProject
10-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HyperbolicDownloaderApi", "HyperbolicDownloaderApi\HyperbolicDownloaderApi.csproj", "{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}"
8+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HyperbolicDownloaderApi", "HyperbolicDownloaderApi\HyperbolicDownloaderApi.csproj", "{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}"
119
EndProject
1210
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CA4F21C6-5B63-46C1-8576-91BB3FAE4FA7}"
1311
ProjectSection(SolutionItems) = preProject
@@ -24,10 +22,6 @@ Global
2422
{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}.Debug|Any CPU.Build.0 = Debug|Any CPU
2523
{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}.Release|Any CPU.ActiveCfg = Release|Any CPU
2624
{7BA90CAF-36A1-4D55-9CE2-E498ECC1B62D}.Release|Any CPU.Build.0 = Release|Any CPU
27-
{E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
28-
{E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Debug|Any CPU.Build.0 = Debug|Any CPU
29-
{E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Release|Any CPU.ActiveCfg = Release|Any CPU
30-
{E1CE6E07-F8A6-447F-837D-9D1943A42E96}.Release|Any CPU.Build.0 = Release|Any CPU
3125
{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
3226
{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}.Debug|Any CPU.Build.0 = Debug|Any CPU
3327
{45ACEEC6-9AE4-4DA5-9A08-E22F1EBA7E22}.Release|Any CPU.ActiveCfg = Release|Any CPU

HyperbolicDownloader/HyperbolicDownloaderCli.csproj renamed to HyperbolicDownloader/HyperbolicDownloader.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
</ItemGroup>
1313

1414
<ItemGroup>
15-
<PackageReference Include="Console.Commander.NET" Version="1.0.0" />
15+
<PackageReference Include="Console.Commander.NET" Version="1.0.1" />
1616
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" />
1717
</ItemGroup>
1818

HyperbolicDownloader/InputHandler.cs

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22

33
using HyperbolicDownloaderApi.Commands;
44
using HyperbolicDownloaderApi.FileProcessing;
5+
using HyperbolicDownloaderApi.Networking;
56

67
using Stone_Red_Utilities.ConsoleExtentions;
78

8-
namespace HyperbolicDownloaderApi;
9+
namespace HyperbolicDownloader;
910

1011
internal class InputHandler
1112
{
12-
private readonly HostsManager hostsManager;
1313
private readonly Commander commander = new Commander();
1414
private bool exit = false;
1515

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

23-
this.hostsManager = hostsManager;
23+
_ = commander.Register(input => commander.PrintHelp(input), "help");
24+
_ = commander.Register(_ => Console.Clear(), (HelpText)"Clears the console.", "clear", "cls");
25+
_ = commander.Register(_ => exit = true, (HelpText)"Exits the application.", "exit", "quit");
26+
_ = commander.Register(clientCommands.ShowInfo, (HelpText)"Displays the private and public IP address.", "info", "inf");
27+
_ = commander.Register(hostCommands.Discover, (HelpText)"Tries to find other active hosts on the local network.", "discover", "disc");
2428

25-
commander.Register((_) => Console.Clear(), "clear", "cls");
26-
commander.Register(Exit, "exit", "quit");
27-
commander.Register(clientCommands.ShowInfo, "info", "inf");
28-
commander.Register(hostCommands.Discover, "discover", "disc");
29+
Command getCommand = commander.Register(downloadCommands.GetFile, (HelpText)"Attempts to retrieve a file from another host using a hash.", "get");
30+
_ = getCommand.Register(downloadCommands.GetFileFrom, (HelpText)"Attempts to retrieve a file from another host using a .hyper file.", "from");
2931

30-
Command getCommand = commander.Register(downloadCommands.GetFile, "get");
31-
getCommand.Register(downloadCommands.GetFileFrom, "from");
32+
Command generateCommad = commander.Register(fileCommands.GenerateFileFull, (HelpText)"Generates a .hyper file from a file hash.", "generate", "gen");
33+
_ = 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");
3234

33-
Command generateCommad = commander.Register(fileCommands.GenerateFileFull, "generate", "gen");
34-
generateCommad.Register(fileCommands.GenerateFileSingle, "noscan");
35+
Command addCommand = commander.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "add");
36+
_ = addCommand.Register(fileCommands.AddFile, (HelpText)"Adds a file to the tracking list.", "file");
37+
_ = addCommand.Register(hostCommands.AddHost, (HelpText)"Adds a host to the list of known hosts.", "host");
3538

36-
Command addCommand = commander.Register(fileCommands.AddFile, "add");
37-
addCommand.Register(hostCommands.AddHost, "host");
38-
addCommand.Register(fileCommands.AddFile, "file");
39+
Command removeCommand = commander.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "remove", "rm");
40+
_ = removeCommand.Register(fileCommands.RemoveFile, (HelpText)"Removes a file from the tracking list.", "file");
41+
_ = removeCommand.Register(hostCommands.RemoveHost, (HelpText)"Removes a host from the list of known hosts.", "host");
3942

40-
Command removeCommand = commander.Register(fileCommands.RemoveFile, "remove", "rm");
41-
removeCommand.Register(hostCommands.RemoveHost, "host");
42-
removeCommand.Register(fileCommands.RemoveFile, "file");
43+
Command listCommand = commander.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "list", "ls");
44+
_ = listCommand.Register(fileCommands.ListFiles, (HelpText)"Lists all files.", "files");
45+
_ = listCommand.Register(hostCommands.ListHosts, (HelpText)"lists all hosts.", "hosts");
4346

44-
Command listCommand = commander.Register(fileCommands.ListFiles, "list", "ls");
45-
listCommand.Register(fileCommands.ListFiles, "files");
46-
listCommand.Register(hostCommands.ListHosts, "hosts");
47-
48-
commander.Register(hostCommands.CheckActiveHosts, "status", "check");
47+
_ = commander.Register(hostCommands.CheckActiveHosts, (HelpText)"Checks the status of known hosts.", "status", "check");
4948
}
5049

5150
public void ReadInput()
@@ -61,7 +60,7 @@ public void ReadInput()
6160
Console.CursorVisible = false;
6261
try
6362
{
64-
if (!commander.Execute(input))
63+
if (!commander.Execute(input, out _))
6564
{
6665
ConsoleExt.WriteLine("Unknown command!", ConsoleColor.Red);
6766
}
@@ -72,10 +71,4 @@ public void ReadInput()
7271
}
7372
}
7473
}
75-
76-
private void Exit(string _)
77-
{
78-
hostsManager.SaveHosts();
79-
exit = true;
80-
}
8174
}

HyperbolicDownloader/Program.cs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66

77
using System.Text.Json;
88

9-
namespace HyperbolicDownloaderApi;
9+
namespace HyperbolicDownloader;
1010

1111
internal static class Program
1212
{
1313
private static readonly ApiManager apiManager = new ApiManager();
1414

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

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

3636
if (args.Length > 0 && File.Exists(args[0]))
3737
{
38-
Commands.DownloadCommands downloadCommands = new Commands.DownloadCommands(apiManager.HostsManager, apiManager.FilesManager);
38+
HyperbolicDownloaderApi.Commands.DownloadCommands downloadCommands = new HyperbolicDownloaderApi.Commands.DownloadCommands(apiManager.HostsManager, apiManager.FilesManager);
3939
downloadCommands.GetFileFrom(args[0]);
4040
Console.WriteLine("Do you want to continue using this instance? [y/N]");
4141
if (char.ToLower(Console.ReadKey().KeyChar) != 'y')
@@ -45,14 +45,25 @@ private static async Task Main(string[] args)
4545
Console.WriteLine();
4646
}
4747

48+
await Initialize();
49+
50+
inputHandler.ReadInput();
51+
Close();
52+
}
53+
54+
private static async Task Initialize()
55+
{
4856
Console.WriteLine("Searching for a UPnP/NAT-PMP device...");
4957
_ = await ApiManager.OpenPorts();
5058

5159
ConsoleExt.WriteLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()} ", ConsoleColor.Green);
5260
ConsoleExt.WriteLine($"The private port is: {ApiConfiguration.PrivatePort}", ConsoleColor.Green);
5361

5462
Console.WriteLine("Starting TCP listener...");
55-
apiManager.StartTcpListener();
63+
if (!apiManager.StartTcpListener())
64+
{
65+
_ = Console.ReadLine();
66+
}
5667

5768
Console.WriteLine("Starting broadcast listener...");
5869
apiManager.StartBroadcastListener();
@@ -74,9 +85,6 @@ private static async Task Main(string[] args)
7485
Console.WriteLine($"{activeHostsCount} active host(s).");
7586

7687
ConsoleExt.WriteLine("Ready", ConsoleColor.Green);
77-
78-
inputHandler.ReadInput();
79-
ApiManager.ClosePorts();
8088
}
8189

8290
private static void ApiManager_OnNotificationMessageRecived(object? sender, NotificationMessageEventArgs e)
@@ -90,7 +98,7 @@ private static void ApiManager_OnNotificationMessageRecived(object? sender, Noti
9098
}
9199
}
92100

93-
private static void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
101+
private static void Close()
94102
{
95103
ApiManager.ClosePorts();
96104
apiManager.HostsManager.SaveHosts();

HyperbolicDownloaderApi/Commands/DownloadCommands.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ public void GetFile(string hash)
152152

153153
if (!Directory.Exists(directoryPath))
154154
{
155-
Directory.CreateDirectory(directoryPath);
155+
_ = Directory.CreateDirectory(directoryPath);
156156
}
157157

158158
using FileStream? fileStream = new FileStream(filePath, FileMode.Create);

HyperbolicDownloaderApi/Commands/FileCommands.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public void GenerateFileSingle(string hash)
7272
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles");
7373
if (!Directory.Exists(directoryPath))
7474
{
75-
Directory.CreateDirectory(directoryPath);
75+
_ = Directory.CreateDirectory(directoryPath);
7676
}
7777

7878
hash = hash.Trim().ToLower();
@@ -111,7 +111,7 @@ public void GenerateFileFull(string hash)
111111
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles");
112112
if (!Directory.Exists(directoryPath))
113113
{
114-
Directory.CreateDirectory(directoryPath);
114+
_ = Directory.CreateDirectory(directoryPath);
115115
}
116116

117117
hash = hash.Trim().ToLower();

HyperbolicDownloaderApi/Commands/HostCommands.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,13 @@ public HostCommands(HostsManager hostsManager)
1919
public void Discover(string _)
2020
{
2121
ApiManager.SendNotificationMessageNewLine("Running local discovery routine...", NotificationMessageType.Info);
22+
23+
int hostsCountBefore = hostsManager.Count;
24+
2225
BroadcastClient.Send(ApiConfiguration.BroadcastPort, ApiConfiguration.PrivatePort.ToString());
2326
Thread.Sleep(3000);
27+
28+
ApiManager.SendNotificationMessageNewLine($"Found {hostsManager.Count - hostsCountBefore} host(s)", NotificationMessageType.Info);
2429
}
2530

2631
public void CheckActiveHosts(string _)
@@ -72,7 +77,7 @@ public void RemoveHost(string args)
7277
string portInput = parts[1];
7378

7479
_ = int.TryParse(portInput, out int port);
75-
if (port < 1000 || port >= 6000)
80+
if (port is < 1000 or >= 6000)
7681
{
7782
ApiManager.SendNotificationMessageNewLine("Invalid port number!", NotificationMessageType.Error);
7883
return;
@@ -112,7 +117,7 @@ public void AddHost(string args)
112117

113118
_ = int.TryParse(portInput, out int port);
114119

115-
if (port < 1000 || port >= 6000)
120+
if (port is < 1000 or >= 6000)
116121
{
117122
ApiManager.SendNotificationMessageNewLine("Invalid port number!", NotificationMessageType.Error);
118123
return;
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Reflection;
22

33
namespace HyperbolicDownloaderApi.Managment;
4+
45
public static class ApiConfiguration
56
{
67
public const int BroadcastPort = 2155;
@@ -9,5 +10,4 @@ public static class ApiConfiguration
910
public static string BasePath { get; } = Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location) ?? string.Empty;
1011
public static string HostsFilePath { get; } = Path.Combine(BasePath, "Hosts.json");
1112
public static string FilesInfoPath { get; } = Path.Combine(BasePath, "Files.json");
12-
13-
}
13+
}

HyperbolicDownloaderApi/Managment/ApiManager.cs

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,10 @@ public ApiManager()
3535

3636
if (device is not null)
3737
{
38-
ipAddress = (device.GetExternalIPAsync()).GetAwaiter().GetResult()?.ToString();
38+
ipAddress = device.GetExternalIPAsync().GetAwaiter().GetResult()?.ToString();
3939
}
4040

41-
if (ipAddress is null || ipAddress == "0.0.0.0")
41+
if (ipAddress is null or "0.0.0.0")
4242
{
4343
ipAddress = NetworkUtilities.GetIP4Adress()?.ToString();
4444
port = ApiConfiguration.PrivatePort;
@@ -115,7 +115,7 @@ public void StartBroadcastListener()
115115
broadcastClient.OnBroadcastRecived += BroadcastClient_OnBroadcastRecived;
116116
}
117117

118-
public void StartTcpListener()
118+
public bool StartTcpListener()
119119
{
120120
try
121121
{
@@ -128,30 +128,35 @@ public void StartTcpListener()
128128
catch (SocketException ex)
129129
{
130130
SendNotificationMessageNewLine($"An error occurred while starting the TCP listener! Error message: {ex.Message}", NotificationMessageType.Error); // net stop hens && net start hns
131-
Console.ReadKey();
131+
return false;
132132
}
133+
134+
return true;
133135
}
134136

135137
private async void BroadcastClient_OnBroadcastRecived(object? sender, BroadcastRecivedEventArgs recivedEventArgs)
136138
{
137-
Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {recivedEventArgs.IPEndPoint.Address}");
139+
IPAddress remoteIpAddress = recivedEventArgs.IPEndPoint.Address;
140+
141+
Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {remoteIpAddress}");
138142
List<NetworkSocket> hostsToSend = HostsManager.ToList();
139143

140144
NetworkSocket? localSocket = GetLocalSocket();
141145

142-
if (localSocket is null)
146+
if (localSocket is null || remoteIpAddress.Equals(PublicIpAddress) || remoteIpAddress.Equals(NetworkUtilities.GetIP4Adress()))
143147
{
148+
Debug.WriteLine("Invalid broadcast!");
144149
return;
145150
}
146151

147-
hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IPEndPoint.Address.ToString());
152+
_ = hostsToSend.RemoveAll(x => x.IPAddress == remoteIpAddress.ToString());
148153
hostsToSend.Add(localSocket);
149154

150155
bool success = int.TryParse(recivedEventArgs.Message, out int remotePort);
151156

152157
if (success)
153158
{
154-
HostsManager.Add(new NetworkSocket(recivedEventArgs.IPEndPoint.Address.ToString(), remotePort, DateTime.Now));
159+
HostsManager.Add(new NetworkSocket(remoteIpAddress.ToString(), remotePort, DateTime.Now));
155160
try
156161
{
157162
await NetworkClient.SendAsync(recivedEventArgs.IPEndPoint.Address, remotePort, "DiscoverAnswer", hostsToSend);
@@ -180,7 +185,7 @@ private async void GetHostList(object? sender, MessageRecivedEventArgs<NetworkSo
180185
return;
181186
}
182187

183-
hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IpAddress.ToString());
188+
_ = hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IpAddress.ToString());
184189
hostsToSend.Add(localSocket);
185190

186191
if (recivedEventArgs.Data.Port != 0)

HyperbolicDownloaderApi/Networking/BroadcastClient.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public static void Send(int port, string message)
4343
byte[] sendbuf = Encoding.ASCII.GetBytes(message);
4444
IPEndPoint ep = new IPEndPoint(broadcast, port);
4545

46-
socket.SendTo(sendbuf, ep);
46+
_ = socket.SendTo(sendbuf, ep);
4747
}
4848

4949
public void StartListening(int port)
@@ -58,7 +58,7 @@ public void StartListening(int port)
5858
udpListener = new UdpClient(port);
5959
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
6060

61-
Task.Run(() =>
61+
_ = Task.Run(() =>
6262
{
6363
while (IsListening)
6464
{

0 commit comments

Comments
 (0)