Improve code structure

- Add separate API project
- Add notification system
This commit is contained in:
Stone_Red
2022-02-24 22:56:45 +01:00
parent 6ffdc720a4
commit cf7f952012
28 changed files with 590 additions and 488 deletions
@@ -0,0 +1,20 @@
using HyperbolicDownloaderApi.Managment;
using HyperbolicDownloaderApi.Networking;
namespace HyperbolicDownloaderApi.Commands;
public class ClientCommands
{
public void ShowInfo(string _)
{
if (ApiManager.PublicIpAddress is not null)
{
ApiManager.SendMessageNewLine($"The public IP address is: {ApiManager.PublicIpAddress}", NotificationMessageType.Success);
ApiManager.SendMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Success);
ApiManager.SendMessageNewLine(string.Empty, NotificationMessageType.Raw);
}
ApiManager.SendMessageNewLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()}", NotificationMessageType.Success);
ApiManager.SendMessageNewLine($"The private port is: {ApiConfiguration.PrivatePort}", NotificationMessageType.Success);
}
}
@@ -0,0 +1,235 @@
using HyperbolicDownloaderApi.FileProcessing;
using HyperbolicDownloaderApi.Managment;
using HyperbolicDownloaderApi.Networking;
using Stone_Red_Utilities.StringExtentions;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
namespace HyperbolicDownloaderApi.Commands;
public class DownloadCommands
{
private readonly HostsManager hostsManager;
private readonly FilesManager filesManager;
public DownloadCommands(HostsManager hostsManager, FilesManager filesManager)
{
this.hostsManager = hostsManager;
this.filesManager = filesManager;
}
public void GetFileFrom(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
ApiManager.SendMessageNewLine("Path is empty!", NotificationMessageType.Error);
return;
}
string fullPath = Path.GetFullPath(path);
if (!File.Exists(fullPath))
{
ApiManager.SendMessageNewLine("Invalid file path!", NotificationMessageType.Error);
}
string json = File.ReadAllText(fullPath);
PublicHyperFileInfo? publicHyperFileInfo = JsonSerializer.Deserialize<PublicHyperFileInfo>(json);
if (publicHyperFileInfo == null)
{
ApiManager.SendMessageNewLine("Parsing file failed!", NotificationMessageType.Error);
return;
}
hostsManager.AddRange(publicHyperFileInfo.Hosts);
GetFile(publicHyperFileInfo.Hash);
}
public void GetFile(string hash)
{
if (string.IsNullOrEmpty(hash))
{
ApiManager.SendMessageNewLine("No hash value specified!", NotificationMessageType.Error);
return;
}
hash = hash.Trim().ToLower();
foreach (NetworkSocket host in hostsManager.ToList())
{
bool validIpAdress = IPAddress.TryParse(host.IPAddress, out IPAddress? ipAddress);
if (!validIpAdress)
{
hostsManager.Remove(host, true);
continue;
}
ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning);
Console.CursorLeft = 0;
Task<bool> sendTask = NetworkClient.SendAsync<bool>(ipAddress!, host.Port, "HasFile", hash);
_ = sendTask.Wait(1000);
if (!sendTask.IsCompletedSuccessfully)
{
Console.CursorLeft = 0;
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error);
hostsManager.Remove(host);
continue;
}
else if (!sendTask.Result)
{
host.LastActive = DateTime.Now;
ApiManager.SendMessageNewLine($"{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...");
using TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ipAddress!, host.Port);
tcpClient.ReceiveBufferSize = 64000;
NetworkStream nwStream = tcpClient.GetStream();
byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
byte[] reciveBuffer = new byte[64000];
byte[] bytesToSend = Encoding.ASCII.GetBytes($"Download {hash}");
nwStream.Write(bytesToSend);
nwStream.ReadTimeout = 30000;
int bytesRead;
try
{
bytesRead = nwStream.Read(buffer, 0, tcpClient.ReceiveBufferSize);
}
catch (IOException)
{
ApiManager.SendMessageNewLine(string.Empty);
ApiManager.SendMessageNewLine("Lost connection to other host!", NotificationMessageType.Error);
continue;
}
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
string[] parts = dataReceived.Split('/');
if (parts.Length == 2) //If received data does not contain 2 parts -> error
{
bool validFileSize = int.TryParse(parts[0], out int fileSize);
if (!validFileSize || fileSize <= 0)
{
ApiManager.SendMessageNewLine("Invalid file size!", NotificationMessageType.Error);
continue;
}
string fileName = parts[1].ToFileName();
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "Downloads");
string filePath = Path.Combine(directoryPath, fileName);
ApiManager.SendMessageNewLine($"File name: {fileName}");
ApiManager.SendMessageNewLine($"Starting download...");
int totalBytesRead = 0;
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
using FileStream? fileStream = new FileStream(filePath, FileMode.Create);
int bytesInOneSecond = 0;
int unitsPerSecond = 0;
string unit = "Kb";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (totalBytesRead < fileSize)
{
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 = Math.Min(bytesRead, fileSize - totalBytesRead);
fileStream.Write(reciveBuffer, 0, bytesRead);
totalBytesRead += bytesRead;
bytesInOneSecond += bytesRead;
if (stopWatch.ElapsedMilliseconds >= 1000)
{
unitsPerSecond = (unitsPerSecond + bytesInOneSecond) / 2;
if (unitsPerSecond > 125000)
{
unitsPerSecond /= 125000;
unit = "Mb";
}
else
{
unitsPerSecond /= 125;
unit = "Kb";
}
bytesInOneSecond = 0;
stopWatch.Restart();
}
ApiManager.SendMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] ");
}
fileStream.Close();
if (totalBytesRead < fileSize)
{
continue;
}
ApiManager.SendMessageNewLine(string.Empty);
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.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}");
ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success);
stopWatch.Stop();
hostsManager.SaveHosts();
return;
}
else
{
ApiManager.SendMessageNewLine(dataReceived, NotificationMessageType.Error);
}
}
ApiManager.SendMessageNewLine("None of the available hosts have the requested file!", NotificationMessageType.Error);
hostsManager.SaveHosts();
}
}
@@ -0,0 +1,186 @@
using HyperbolicDownloaderApi.FileProcessing;
using HyperbolicDownloaderApi.Managment;
using HyperbolicDownloaderApi.Networking;
using System.Net;
using System.Text.Json;
namespace HyperbolicDownloaderApi.Commands;
public class FileCommands
{
private readonly HostsManager hostsManager;
private readonly FilesManager filesManager;
public FileCommands(HostsManager hostsManager, FilesManager filesManager)
{
this.hostsManager = hostsManager;
this.filesManager = filesManager;
}
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}");
}
else
{
ApiManager.SendMessageNewLine(message, NotificationMessageType.Error);
}
}
public void RemoveFile(string hash)
{
hash = hash.Trim().ToLower();
if (filesManager.TryRemove(hash))
{
ApiManager.SendMessageNewLine($"Successfully removed file!", NotificationMessageType.Success);
}
else
{
ApiManager.SendMessageNewLine("The file is not being tracked!", NotificationMessageType.Error);
}
}
public void ListFiles(string _)
{
int index = 0;
List<PrivateHyperFileInfo> fileInfos = filesManager.ToList();
if (fileInfos.Count == 0)
{
ApiManager.SendMessageNewLine("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);
}
Console.CursorTop--;
}
public void GenerateFileSingle(string hash)
{
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
hash = hash.Trim().ToLower();
if (!filesManager.TryGet(hash, out PrivateHyperFileInfo? localHyperFileInfo))
{
ApiManager.SendMessageNewLine("The file is not being tracked!", NotificationMessageType.Error);
return;
}
string fileName = Path.GetFileName(localHyperFileInfo!.FilePath);
string filePath = Path.Combine(directoryPath, $"{fileName}.hyper");
PublicHyperFileInfo publicHyperFileInfo = new PublicHyperFileInfo(hash);
NetworkSocket? localHost = ApiManager.GetLocalSocket();
if (localHost is null)
{
ApiManager.SendMessageNewLine("Network error!", NotificationMessageType.Error);
return;
}
publicHyperFileInfo.Hosts.Add(localHost);
JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(publicHyperFileInfo, options);
File.WriteAllText(filePath, json);
ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success);
ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}");
}
public void GenerateFileFull(string hash)
{
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "GeneratedFiles");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
hash = hash.Trim().ToLower();
if (!filesManager.TryGet(hash, out PrivateHyperFileInfo? localHyperFileInfo))
{
ApiManager.SendMessageNewLine("The file is not being tracked!", NotificationMessageType.Error);
return;
}
string fileName = Path.GetFileName(localHyperFileInfo!.FilePath);
string filePath = Path.Combine(directoryPath, $"{fileName}.hyper");
PublicHyperFileInfo publicHyperFileInfo = new PublicHyperFileInfo(hash);
NetworkSocket? localHost = ApiManager.GetLocalSocket();
if (localHost is null)
{
ApiManager.SendMessageNewLine("Network error!", NotificationMessageType.Error);
return;
}
foreach (NetworkSocket host in hostsManager.ToList())
{
bool validIpAdress = IPAddress.TryParse(host.IPAddress, out IPAddress? ipAddress);
if (!validIpAdress)
{
hostsManager.Remove(host, true);
continue;
}
ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning);
Console.CursorLeft = 0;
Task<bool> sendTask = NetworkClient.SendAsync<bool>(ipAddress!, host.Port, "HasFile", hash);
_ = sendTask.Wait(1000);
if (!sendTask.IsCompletedSuccessfully)
{
Console.CursorLeft = 0;
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error);
hostsManager.Remove(host);
continue;
}
else if (!sendTask.Result)
{
host.LastActive = DateTime.Now;
ApiManager.SendMessageNewLine($"{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);
publicHyperFileInfo.Hosts.Add(host);
}
publicHyperFileInfo.Hosts.Add(localHost);
JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(publicHyperFileInfo, options);
File.WriteAllText(filePath, json);
ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success);
ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}");
}
}
@@ -0,0 +1,148 @@
using HyperbolicDownloaderApi.Managment;
using HyperbolicDownloaderApi.Networking;
using System.Net;
using System.Net.Sockets;
namespace HyperbolicDownloaderApi.Commands;
public class HostCommands
{
private readonly HostsManager hostsManager;
public HostCommands(HostsManager hostsManager)
{
this.hostsManager = hostsManager;
}
public void Discover(string _)
{
ApiManager.SendMessageNewLine("Running local discovery routine...", NotificationMessageType.Raw);
BroadcastClient.Send(ApiConfiguration.BroadcastPort, ApiConfiguration.PrivatePort.ToString());
Thread.Sleep(3000);
}
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.SendMessageNewLine(string.Empty, NotificationMessageType.Raw);
ApiManager.SendMessageNewLine($"{hostsManager.Count} known host(s).", NotificationMessageType.Raw);
ApiManager.SendMessageNewLine($"{activeHostsCount} active host(s).", NotificationMessageType.Raw);
}
public void ListHosts(string _)
{
int index = 0;
List<NetworkSocket> hosts = hostsManager.ToList();
if (hosts.Count == 0)
{
ApiManager.SendMessageNewLine("No known hosts", NotificationMessageType.Warning);
return;
}
foreach (NetworkSocket host in hosts)
{
index++;
ApiManager.SendMessageNewLine($"{index}) {host.IPAddress}:{host.Port}", NotificationMessageType.Raw);
ApiManager.SendMessageNewLine($"Last active: {host.LastActive}", NotificationMessageType.Raw);
ApiManager.SendMessageNewLine(string.Empty, NotificationMessageType.Raw);
}
Console.CursorTop--;
}
public void RemoveHost(string args)
{
string[] parts = args.Split(":");
if (parts.Length != 2)
{
ApiManager.SendMessageNewLine("Invalid format! Use this format: (xxx.xxx.xxx.xxx:yyyy)", NotificationMessageType.Error);
return;
}
string ipAddressInput = parts[0];
string portInput = parts[1];
_ = int.TryParse(portInput, out int port);
if (port < 1000 || port >= 6000)
{
ApiManager.SendMessageNewLine("Invalid port number!", NotificationMessageType.Error);
return;
}
if (!IPAddress.TryParse(ipAddressInput, out IPAddress? ipAddress))
{
ApiManager.SendMessageNewLine("Invalid IP address!", NotificationMessageType.Error);
return;
}
NetworkSocket hostToRemove = new NetworkSocket(ipAddress.ToString(), port, DateTime.MinValue);
if (!hostsManager.Contains(hostToRemove))
{
ApiManager.SendMessageNewLine("Host not in list", NotificationMessageType.Error);
return;
}
hostsManager.Remove(new NetworkSocket(ipAddress.ToString(), port, DateTime.MinValue), true);
ApiManager.SendMessageNewLine($"Successfully Removed host!", NotificationMessageType.Success);
}
public void AddHost(string args)
{
string[] parts = args.Split(":");
if (parts.Length != 2)
{
ApiManager.SendMessageNewLine("Invalid format! Use this format: (xxx.xxx.xxx.xxx:yyyy)", NotificationMessageType.Error);
return;
}
string ipAddressInput = parts[0];
string portInput = parts[1];
_ = int.TryParse(portInput, out int port);
if (port < 1000 || port >= 6000)
{
ApiManager.SendMessageNewLine("Invalid port number!", NotificationMessageType.Error);
}
else if (IPAddress.TryParse(ipAddressInput, out IPAddress? ipAddress))
{
try
{
ApiManager.SendMessageNewLine("Waiting for response...", NotificationMessageType.Raw);
NetworkSocket? localSocket = ApiManager.GetLocalSocket() ?? new NetworkSocket("0.0.0.0", 0, DateTime.MinValue);
List<NetworkSocket>? recivedHosts = NetworkClient.Send<List<NetworkSocket>>(ipAddress, port, "GetHostsList", localSocket);
if (recivedHosts is not null)
{
ApiManager.SendMessageNewLine($"Success! Added {recivedHosts.Count} new host(s).", NotificationMessageType.Success);
hostsManager.AddRange(recivedHosts);
}
else
{
ApiManager.SendMessageNewLine($"Invalid response!", NotificationMessageType.Error);
}
}
catch (SocketException ex)
{
ApiManager.SendMessageNewLine($"Invalid host! Error message: {ex.Message}", NotificationMessageType.Error);
}
catch (IOException ex)
{
ApiManager.SendMessageNewLine($"Invalid host! Error message: {ex.Message}", NotificationMessageType.Error);
}
}
else
{
ApiManager.SendMessageNewLine("Invalid IP address!", NotificationMessageType.Error);
}
}
}
@@ -0,0 +1,33 @@
using System.IO.Compression;
namespace HyperbolicDownloaderApi.FileProcessing;
internal static class FileCompressor
{
public static void CompressFile(string inputFilePath, string compressedFilePath)
{
using FileStream originalFileStream = File.Open(inputFilePath, FileMode.Open);
using FileStream compressedFileStream = File.Create(compressedFilePath);
using GZipStream? compressor = new GZipStream(compressedFileStream, CompressionMode.Compress);
originalFileStream.CopyTo(compressor);
}
public static void DecompressFile(string compressedFilePath, string outputFilePath)
{
using FileStream compressedFileStream = File.Open(compressedFilePath, FileMode.Open);
using FileStream outputFileStream = File.Create(outputFilePath);
using GZipStream? decompressor = new GZipStream(compressedFileStream, CompressionMode.Decompress);
decompressor.CopyTo(outputFileStream);
}
public static IEnumerable<byte[]> ReadChunks(string path, int chunkSize)
{
byte[] buffer = new byte[chunkSize];
using FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
using BufferedStream bs = new BufferedStream(fs);
while (bs.Read(buffer, 0, chunkSize) != 0)
{
yield return buffer;
}
}
}
@@ -0,0 +1,29 @@
using System.Security.Cryptography;
namespace HyperbolicDownloaderApi.FileProcessing;
internal static class FileValidator
{
public static async Task<string> CalculateHashAsync(string filePath)
{
using SHA512 sha = SHA512.Create();
using FileStream? stream = File.OpenRead(filePath);
byte[]? hash = await sha.ComputeHashAsync(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
public static string CalculateHash(string filePath)
{
return CalculateHashAsync(filePath).GetAwaiter().GetResult();
}
public static async Task<bool> ValidateHashAsync(string filePath, string hash)
{
return await CalculateHashAsync(filePath) == hash;
}
public static bool ValidateHash(string filePath, string hash)
{
return CalculateHash(filePath) == hash;
}
}
@@ -0,0 +1,98 @@
using HyperbolicDownloaderApi.Managment;
using System.Text.Json;
namespace HyperbolicDownloaderApi.FileProcessing;
public class FilesManager
{
private readonly List<PrivateHyperFileInfo> files = new List<PrivateHyperFileInfo>();
public bool TryAdd(string filePath, out PrivateHyperFileInfo? fileInfo, out string? errorMessage)
{
if (string.IsNullOrWhiteSpace(filePath))
{
fileInfo = null;
errorMessage = "Path is empty!";
return false;
}
string fullPath = Path.GetFullPath(filePath);
if (!File.Exists(fullPath))
{
fileInfo = null;
errorMessage = "Invalid file path!";
return false;
}
string hash = FileValidator.CalculateHash(filePath);
if (Contains(hash))
{
fileInfo = null;
errorMessage = "File already tracked!";
return false;
}
fileInfo = new PrivateHyperFileInfo(hash, fullPath);
files.Add(fileInfo);
SaveFiles();
errorMessage = null;
return true;
}
public void AddRange(IEnumerable<PrivateHyperFileInfo> fileInfos)
{
foreach (PrivateHyperFileInfo fileInfo in fileInfos)
{
if (File.Exists(fileInfo.FilePath) && !Contains(fileInfo.Hash))
{
files.Add(fileInfo);
}
}
SaveFiles();
}
public bool TryGet(string hash, out PrivateHyperFileInfo? fileInfo)
{
if (Contains(hash))
{
fileInfo = files.First(x => x.Hash == hash);
return true;
}
else
{
fileInfo = null;
return false;
}
}
public bool TryRemove(string hash)
{
int count = files.RemoveAll(f => f.Hash == hash);
SaveFiles();
return count > 0;
}
public bool Contains(string? hash)
{
return files.Any(f => f.Hash == hash);
}
public List<PrivateHyperFileInfo> ToList()
{
return files.ToList();
}
private void SaveFiles()
{
File.WriteAllText(ApiConfiguration.FilesInfoPath, JsonSerializer.Serialize(files));
}
}
@@ -0,0 +1,13 @@
namespace HyperbolicDownloaderApi.FileProcessing;
public class PrivateHyperFileInfo
{
public string Hash { get; set; }
public string FilePath { get; set; }
public PrivateHyperFileInfo(string hash, string filePath)
{
Hash = hash;
FilePath = filePath;
}
}
@@ -0,0 +1,24 @@
using HyperbolicDownloaderApi.Networking;
namespace HyperbolicDownloaderApi.FileProcessing;
public class PublicHyperFileInfo
{
public string Hash { get; set; } = string.Empty;
public List<NetworkSocket> Hosts { get; set; } = new();
public PublicHyperFileInfo()
{
}
public PublicHyperFileInfo(string hash)
{
Hash = hash;
}
public PublicHyperFileInfo(string hash, List<NetworkSocket> hosts)
{
Hash = hash;
Hosts = hosts;
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Open.Nat" Version="2.1.0" />
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" />
</ItemGroup>
</Project>
@@ -0,0 +1,13 @@
using System.Reflection;
namespace HyperbolicDownloaderApi.Managment;
public static class ApiConfiguration
{
public const int BroadcastPort = 2155;
public const int PrivatePort = 3055;
public static int PublicPort { get; set; }
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");
}
@@ -0,0 +1,213 @@
using HyperbolicDownloaderApi.FileProcessing;
using HyperbolicDownloaderApi.Networking;
using Open.Nat;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
namespace HyperbolicDownloaderApi.Managment;
public class ApiManager
{
public static event EventHandler<NotificationMessageEventArgs>? OnNotificationMessageRecived;
public static IPAddress? PublicIpAddress => device?.GetExternalIPAsync().GetAwaiter().GetResult();
public FilesManager FilesManager { get; } = new();
public HostsManager HostsManager { get; } = new();
private static readonly Random random = new();
private static NatDevice? device;
private static Mapping? portMapping;
private readonly BroadcastClient broadcastClient = new BroadcastClient();
private readonly NetworkClient networkClient;
public ApiManager()
{
networkClient = new(FilesManager);
}
public static void ClosePorts()
{
ApiManager.SendMessageNewLine("Closing ports...", NotificationMessageType.Success);
if (device is not null)
{
try
{
IEnumerable<Mapping>? mappings = device.GetAllMappingsAsync().GetAwaiter().GetResult();
foreach (Mapping? mapping in mappings)
{
if (mapping.Description.Contains("HyperbolicDowloader") && mapping.PrivateIP.ToString() == portMapping?.PrivateIP.ToString())
{
device.DeletePortMapAsync(mapping).GetAwaiter().GetResult();
}
}
}
catch (Exception ex)
{
ApiManager.SendMessageNewLine(ex.ToString(), NotificationMessageType.Error);
}
}
ApiManager.SendMessageNewLine("Ports closed!", NotificationMessageType.Warning);
Environment.Exit(0);
}
public static NetworkSocket? GetLocalSocket()
{
int port = ApiConfiguration.PublicPort;
string? ipAddress = null;
if (device is not null)
{
ipAddress = (device.GetExternalIPAsync()).GetAwaiter().GetResult()?.ToString();
}
if (ipAddress is null || ipAddress == "0.0.0.0")
{
ipAddress = NetworkUtilities.GetIP4Adress()?.ToString();
port = ApiConfiguration.PrivatePort;
}
if (ipAddress is null)
{
return null;
}
return new NetworkSocket(ipAddress, port, DateTime.Now);
}
public static async Task<bool> OpenPorts()
{
try
{
ApiConfiguration.PublicPort = random.Next(1000, 6000);
NatDiscoverer? discoverer = new NatDiscoverer();
device = await discoverer.DiscoverDeviceAsync();
IPAddress? ip = await device.GetExternalIPAsync();
ApiManager.SendMessageNewLine($"The public IP address is: {ip} ", NotificationMessageType.Success);
portMapping = new Mapping(Protocol.Tcp, ApiConfiguration.PrivatePort, ApiConfiguration.PublicPort, "HyperbolicDowloader");
await device.CreatePortMapAsync(portMapping);
ApiManager.SendMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Success);
return true;
}
catch (NatDeviceNotFoundException)
{
ApiManager.SendMessageNewLine($"Could not find a UPnP or NAT-PMP device!", NotificationMessageType.Error);
return false;
}
catch (MappingException ex)
{
ApiManager.SendMessageNewLine($"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 void StartBroadcastListener()
{
broadcastClient.StartListening(ApiConfiguration.BroadcastPort);
broadcastClient.OnBroadcastRecived += BroadcastClient_OnBroadcastRecived;
}
public void StartTcpListener()
{
try
{
networkClient.ListenTo<NetworkSocket>("GetHostsList", GetHostList);
networkClient.ListenTo<List<NetworkSocket>>("DiscoverAnswer", DiscoverAnswer);
networkClient.ListenTo<string>("Message", ReciveMessage);
networkClient.ListenTo<string>("HasFile", HasFile);
networkClient.StartListening(ApiConfiguration.PrivatePort);
}
catch (SocketException ex)
{
ApiManager.SendMessageNewLine($"An error occurred while starting the TCP listener! Error message: {ex.Message}", NotificationMessageType.Error); // net stop hns && net start hns
Console.ReadKey();
}
}
private async void BroadcastClient_OnBroadcastRecived(object? sender, BroadcastRecivedEventArgs recivedEventArgs)
{
Debug.WriteLine($"Received broadcast \"{recivedEventArgs.Message}\" from {recivedEventArgs.IPEndPoint.Address}");
List<NetworkSocket> hostsToSend = HostsManager.ToList();
NetworkSocket? localSocket = GetLocalSocket();
if (localSocket is null)
{
return;
}
hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IPEndPoint.Address.ToString());
hostsToSend.Add(localSocket);
bool success = int.TryParse(recivedEventArgs.Message, out int remotePort);
if (success)
{
HostsManager.Add(new NetworkSocket(recivedEventArgs.IPEndPoint.Address.ToString(), remotePort, DateTime.Now));
try
{
await NetworkClient.SendAsync(recivedEventArgs.IPEndPoint.Address, remotePort, "DiscoverAnswer", hostsToSend);
}
catch (SocketException ex)
{
Debug.WriteLine(ex);
}
}
}
private void DiscoverAnswer(object? sender, MessageRecivedEventArgs<List<NetworkSocket>> recivedEventArgs)
{
ApiManager.SendMessageNewLine($"Received answer from {recivedEventArgs.IpAddress}. Returned {recivedEventArgs.Data.Count} host(s).", NotificationMessageType.Raw);
HostsManager.AddRange(recivedEventArgs.Data);
}
private async void GetHostList(object? sender, MessageRecivedEventArgs<NetworkSocket> recivedEventArgs)
{
List<NetworkSocket> hostsToSend = HostsManager.ToList();
NetworkSocket? localSocket = GetLocalSocket();
if (localSocket is null)
{
return;
}
hostsToSend.RemoveAll(x => x.IPAddress == recivedEventArgs.IpAddress.ToString());
hostsToSend.Add(localSocket);
if (recivedEventArgs.Data.Port != 0)
{
HostsManager.Add(recivedEventArgs.Data);
}
await recivedEventArgs.SendResponseAsync(hostsToSend);
}
private async void HasFile(object? sender, MessageRecivedEventArgs<string> recivedEventArgs)
{
await recivedEventArgs.SendResponseAsync(FilesManager.Contains(recivedEventArgs.Data));
}
private void ReciveMessage(object? sender, MessageRecivedEventArgs<string> recivedEventArgs)
{
ApiManager.SendMessageNewLine($"Received \"{recivedEventArgs.Data}\" from {recivedEventArgs.IpAddress}.", NotificationMessageType.Raw);
}
internal static void SendMessage(string message, NotificationMessageType messageType = NotificationMessageType.Raw)
{
OnNotificationMessageRecived?.Invoke(null, new NotificationMessageEventArgs(messageType, message));
}
internal static void SendMessageNewLine(string message, NotificationMessageType messageType = NotificationMessageType.Raw)
{
OnNotificationMessageRecived?.Invoke(null, new NotificationMessageEventArgs(messageType, message + Environment.NewLine));
}
}
@@ -0,0 +1,21 @@
namespace HyperbolicDownloaderApi.Managment;
public class NotificationMessageEventArgs : EventArgs
{
public NotificationMessageType NotificationMessageType { get; }
public string? Message { get; }
public NotificationMessageEventArgs(NotificationMessageType notificationMessageType, string? message)
{
NotificationMessageType = notificationMessageType;
Message = message;
}
}
public enum NotificationMessageType
{
Raw,
Success,
Warning,
Error
}
@@ -0,0 +1,78 @@
using HyperbolicDownloaderApi.Managment;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
namespace HyperbolicDownloaderApi.Networking;
internal class BroadcastClient
{
public event EventHandler<BroadcastRecivedEventArgs>? OnBroadcastRecived;
public bool IsListening { get; private set; } = false;
private UdpClient? udpListener;
public static void Send(int port, string message)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
EnableBroadcast = true
};
IPAddress? ip4Address = NetworkUtilities.GetIP4Adress();
if (ip4Address is null)
{
ApiManager.SendMessageNewLine("Could not find suitable network adapter!", NotificationMessageType.Error);
return;
}
UnicastIPAddressInformation? addressInformation = NetworkUtilities.GetUnicastIPAddressInformation(ip4Address);
if (addressInformation is null)
{
ApiManager.SendMessageNewLine("Could not find suitable network adapter!", NotificationMessageType.Error);
return;
}
IPAddress broadcast = NetworkUtilities.GetBroadcastAddress(addressInformation);
byte[] sendbuf = Encoding.ASCII.GetBytes(message);
IPEndPoint ep = new IPEndPoint(broadcast, port);
socket.SendTo(sendbuf, ep);
}
public void StartListening(int port)
{
if (IsListening)
{
throw new InvalidOperationException("Already listening!");
}
IsListening = true;
udpListener = new UdpClient(port);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
Task.Run(() =>
{
while (IsListening)
{
byte[] bytes = udpListener.Receive(ref groupEP);
string message = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
OnBroadcastRecived?.Invoke(this, new BroadcastRecivedEventArgs(groupEP, message));
}
});
}
public void StopListening()
{
udpListener?.Close();
IsListening = false;
}
}
@@ -0,0 +1,15 @@
using System.Net;
namespace HyperbolicDownloaderApi.Networking;
internal class BroadcastRecivedEventArgs : EventArgs
{
public BroadcastRecivedEventArgs(IPEndPoint iPEndPoint, string message)
{
IPEndPoint = iPEndPoint;
Message = message;
}
public IPEndPoint IPEndPoint { get; }
public string Message { get; }
}
@@ -0,0 +1,14 @@
namespace HyperbolicDownloaderApi
{
internal class DataContainer
{
public string EventName { get; set; }
public string JsonData { get; set; }
public DataContainer(string eventName, string jsonData)
{
JsonData = jsonData;
EventName = eventName;
}
}
}
@@ -0,0 +1,108 @@
using HyperbolicDownloaderApi.Managment;
using HyperbolicDownloaderApi.Networking;
using System.Net.Sockets;
using System.Text.Json;
namespace HyperbolicDownloaderApi;
public class HostsManager
{
private List<NetworkSocket> hosts = new List<NetworkSocket>();
public int Count => hosts.Count;
public void AddRange(IEnumerable<NetworkSocket> hosts)
{
foreach (NetworkSocket host in hosts)
{
if (!Contains(host))
{
this.hosts.Add(host);
}
}
SaveHosts();
}
public void Add(NetworkSocket host)
{
if (!Contains(host))
{
hosts.Add(host);
}
SaveHosts();
}
public void Remove(NetworkSocket host, bool forceRemove = false)
{
if (DateTime.Now - host.LastActive >= new TimeSpan(24, 0, 0) || forceRemove)
{
hosts.RemoveAll(x => x.IPAddress == host.IPAddress && x.Port == host.Port);
}
SaveHosts();
}
public bool Contains(NetworkSocket host)
{
return hosts.Any(x => x.IPAddress == host.IPAddress && x.Port == host.Port);
}
public int CheckHostsActivity()
{
List<NetworkSocket> hostsToRemove = new List<NetworkSocket>();
int activeHostsCount = 0;
foreach (NetworkSocket host in hosts)
{
ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning);
using TcpClient tcpClient = new TcpClient();
try
{
tcpClient.ConnectAsync(host.IPAddress, host.Port).Wait(1000);
Console.CursorLeft = 0;
if (tcpClient.Connected)
{
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Active", NotificationMessageType.Success);
host.LastActive = DateTime.Now;
activeHostsCount++;
}
else
{
if (DateTime.Now - host.LastActive >= new TimeSpan(24, 0, 0))
{
hostsToRemove.Add(host);
}
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error);
}
}
catch
{
if (DateTime.Now - host.LastActive >= new TimeSpan(24, 0, 0))
{
hostsToRemove.Add(host);
}
Console.CursorLeft = 0;
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error);
}
}
foreach (NetworkSocket host in hostsToRemove)
{
hosts.Remove(host);
}
SaveHosts();
return activeHostsCount;
}
public List<NetworkSocket> ToList()
{
return hosts.ToList();
}
public void SaveHosts()
{
hosts = hosts.OrderByDescending(h => h.LastActive).ToList();
File.WriteAllText(ApiConfiguration.HostsFilePath, JsonSerializer.Serialize(hosts));
}
}
@@ -0,0 +1,34 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
namespace HyperbolicDownloaderApi
{
internal class MessageRecivedEventArgs<T> : EventArgs
{
private readonly NetworkStream networkStream;
public MessageRecivedEventArgs(NetworkStream networkStream, IPAddress ipAddress, T data)
{
this.networkStream = networkStream;
Data = data;
IpAddress = ipAddress;
}
public T Data { 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 void SendResponse(object response)
{
SendResponseAsync(response).GetAwaiter().GetResult();
}
}
}
@@ -0,0 +1,204 @@
using HyperbolicDownloaderApi.FileProcessing;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
namespace HyperbolicDownloaderApi.Networking
{
internal class NetworkClient
{
public bool IsListening { get; private set; } = false;
private TcpListener? tcpListener;
private readonly FilesManager filesManager;
private readonly Dictionary<string, (Type type, Delegate method)> events = new();
public NetworkClient(FilesManager filesManager)
{
this.filesManager = filesManager;
}
public static async Task<T?> SendAsync<T>(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);
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))
{
return default;
}
else
{
return JsonSerializer.Deserialize<T>(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<T>(IPAddress remoteIp, int remotePort, string eventName, object data)
{
return SendAsync<T>(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)
{
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<DataContainer>(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)}");
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);
}
client.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public void StopListening()
{
tcpListener?.Stop();
IsListening = false;
}
public void ListenTo<T>(string eventName, EventHandler<MessageRecivedEventArgs<T>> eventHandler)
{
events.Add(eventName, (typeof(T), eventHandler));
}
}
}
@@ -0,0 +1,15 @@
namespace HyperbolicDownloaderApi.Networking;
public class NetworkSocket
{
public string IPAddress { get; set; }
public int Port { get; set; }
public DateTime LastActive { get; set; }
public NetworkSocket(string ipAddress, int port, DateTime lastActive)
{
IPAddress = ipAddress;
Port = port;
LastActive = lastActive;
}
}
@@ -0,0 +1,46 @@
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace HyperbolicDownloaderApi.Networking;
public static class NetworkUtilities
{
public static UnicastIPAddressInformation? GetUnicastIPAddressInformation(IPAddress address)
{
foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
{
if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork && address.Equals(unicastIPAddressInformation.Address))
{
return unicastIPAddressInformation;
}
}
}
return null;
}
public static IPAddress? GetIP4Adress()
{
using Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0);
socket.Connect("8.8.8.8", 65530);
IPEndPoint? endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint?.Address;
}
public static IPAddress GetBroadcastAddress(UnicastIPAddressInformation unicastAddress)
{
return GetBroadcastAddress(unicastAddress.Address, unicastAddress.IPv4Mask);
}
public static IPAddress GetBroadcastAddress(IPAddress address, IPAddress mask)
{
uint ipAddress = BitConverter.ToUInt32(address.GetAddressBytes(), 0);
uint ipMaskV4 = BitConverter.ToUInt32(mask.GetAddressBytes(), 0);
uint broadCastIpAddress = ipAddress | ~ipMaskV4;
return new IPAddress(BitConverter.GetBytes(broadCastIpAddress));
}
}