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);
}
}
}