Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
Stone-Red-Code committed Apr 21, 2022
2 parents 715f5de + f906d45 commit 9f08b5c
Show file tree
Hide file tree
Showing 12 changed files with 174 additions and 161 deletions.
6 changes: 6 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,9 @@

# S4457: Parameter validation in "async"/"await" methods should be wrapped
dotnet_diagnostic.S4457.severity = silent

# CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = silent

# S1172: Unused method parameters should be removed
dotnet_diagnostic.S1172.severity = silent
2 changes: 1 addition & 1 deletion HyperbolicDownloader/HyperbolicDownloaderCli.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

using Stone_Red_Utilities.ConsoleExtentions;

namespace HyperbolicDownloaderApi.UserInterface;
namespace HyperbolicDownloaderApi;

internal class InputHandler
{
Expand Down
1 change: 0 additions & 1 deletion HyperbolicDownloader/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using HyperbolicDownloaderApi.FileProcessing;
using HyperbolicDownloaderApi.Managment;
using HyperbolicDownloaderApi.Networking;
using HyperbolicDownloaderApi.UserInterface;

using Stone_Red_Utilities.ConsoleExtentions;

Expand Down
10 changes: 5 additions & 5 deletions HyperbolicDownloaderApi/Commands/ClientCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ public void ShowInfo(string _)
{
if (ApiManager.PublicIpAddress is not null)
{
ApiManager.SendMessageNewLine($"The public IP address is: {ApiManager.PublicIpAddress}", NotificationMessageType.Info);
ApiManager.SendMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Info);
ApiManager.SendMessageNewLine(string.Empty, NotificationMessageType.Info);
ApiManager.SendNotificationMessageNewLine($"The public IP address is: {ApiManager.PublicIpAddress}", NotificationMessageType.Info);
ApiManager.SendNotificationMessageNewLine($"The public port is: {ApiConfiguration.PublicPort}", NotificationMessageType.Info);
ApiManager.SendNotificationMessageNewLine(string.Empty, NotificationMessageType.Info);
}

ApiManager.SendMessageNewLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()}", NotificationMessageType.Info);
ApiManager.SendMessageNewLine($"The private port is: {ApiConfiguration.PrivatePort}", NotificationMessageType.Info);
ApiManager.SendNotificationMessageNewLine($"The private IP address is: {NetworkUtilities.GetIP4Adress()}", NotificationMessageType.Info);
ApiManager.SendNotificationMessageNewLine($"The private port is: {ApiConfiguration.PrivatePort}", NotificationMessageType.Info);
}
}
177 changes: 89 additions & 88 deletions HyperbolicDownloaderApi/Commands/DownloadCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,23 @@ public void GetFileFrom(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
ApiManager.SendMessageNewLine("Path is empty!", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine("Path is empty!", NotificationMessageType.Error);
return;
}

string fullPath = Path.GetFullPath(path);

if (!File.Exists(fullPath))
{
ApiManager.SendMessageNewLine("Invalid file path!", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine("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);
ApiManager.SendNotificationMessageNewLine("Parsing file failed!", NotificationMessageType.Error);
return;
}

Expand All @@ -55,7 +55,7 @@ public void GetFile(string hash)
{
if (string.IsNullOrEmpty(hash))
{
ApiManager.SendMessageNewLine("No hash value specified!", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine("No hash value specified!", NotificationMessageType.Error);
return;
}

Expand All @@ -71,7 +71,7 @@ public void GetFile(string hash)
continue;
}

ApiManager.SendMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning);
ApiManager.SendNotificationMessage($"{host.IPAddress}:{host.Port} > ???", NotificationMessageType.Warning);

Console.CursorLeft = 0;

Expand All @@ -82,22 +82,22 @@ public void GetFile(string hash)
if (!sendTask.IsCompletedSuccessfully)
{
Console.CursorLeft = 0;
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Inactive", NotificationMessageType.Error);

hostsManager.Remove(host);
continue;
}
else if (!sendTask.Result)
{
host.LastActive = DateTime.Now;
ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Does not have the requested file", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Does not have the requested file", NotificationMessageType.Error);
continue;
}

host.LastActive = DateTime.Now;

ApiManager.SendMessageNewLine($"{host.IPAddress}:{host.Port} > Has the requested file", NotificationMessageType.Success);
ApiManager.SendMessageNewLine("Requesting file...");
ApiManager.SendNotificationMessageNewLine($"{host.IPAddress}:{host.Port} > Has the requested file", NotificationMessageType.Success);
ApiManager.SendNotificationMessageNewLine("Requesting file...");

using TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ipAddress!, host.Port);
Expand All @@ -114,122 +114,123 @@ public void GetFile(string hash)
int bytesRead;
try
{
bytesRead = nwStream.Read(buffer, 0, tcpClient.ReceiveBufferSize);
bytesRead = nwStream.Read(buffer, 0, 1000);
}
catch (IOException)
{
ApiManager.SendMessageNewLine(string.Empty);
ApiManager.SendMessageNewLine("Lost connection to other host!", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine(string.Empty);
ApiManager.SendNotificationMessageNewLine("Lost connection to other host!", NotificationMessageType.Error);
continue;
}

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
if (parts.Length != 2) //If received data does not contain 2 parts -> error
{
bool validFileSize = int.TryParse(parts[0], out int fileSize);
ApiManager.SendNotificationMessageNewLine(dataReceived, NotificationMessageType.Error);
continue;
}

if (!validFileSize || fileSize <= 0)
{
ApiManager.SendMessageNewLine("Invalid file size!", NotificationMessageType.Error);
continue;
}
bool validFileSize = int.TryParse(parts[0], out int fileSize);

string fileName = parts[1].ToFileName();
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "Downloads");
string filePath = Path.Combine(directoryPath, fileName);
if (!validFileSize || fileSize <= 0)
{
ApiManager.SendNotificationMessageNewLine("Invalid file size!", NotificationMessageType.Error);
continue;
}

ApiManager.SendMessageNewLine($"File name: {fileName}");
ApiManager.SendMessageNewLine($"Starting download...");
string fileName = parts[1].ToFileName();
string directoryPath = Path.Combine(ApiConfiguration.BasePath, "Downloads");
string filePath = Path.Combine(directoryPath, fileName);

int totalBytesRead = 0;
ApiManager.SendNotificationMessageNewLine($"File name: {fileName}");
ApiManager.SendNotificationMessageNewLine($"Starting download...");

if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
int totalBytesRead = 0;

using FileStream? fileStream = new FileStream(filePath, FileMode.Create);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}

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

int bytesInOneSecond = 0;
int unitsPerSecond = 0;
string unit = "Kb";
int bytesInOneSecond = 0;
int unitsPerSecond = 0;
string unit = "Kb";

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (totalBytesRead < fileSize)
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (totalBytesRead < fileSize)
{
try
{
try
{
bytesRead = nwStream.Read(reciveBuffer, 0, reciveBuffer.Length);
}
catch (IOException)
{
ApiManager.SendMessageNewLine(string.Empty);
ApiManager.SendMessageNewLine("Lost connection to other host!", NotificationMessageType.Error);
break;
}
bytesRead = nwStream.Read(reciveBuffer, 0, reciveBuffer.Length);
}
catch (IOException ex)
{
Debug.WriteLine(ex);
ApiManager.SendNotificationMessageNewLine(string.Empty);
ApiManager.SendNotificationMessageNewLine("Lost connection to other host!", NotificationMessageType.Error);
break;
}

bytesRead = Math.Min(bytesRead, fileSize - totalBytesRead);
bytesRead = Math.Min(bytesRead, fileSize - totalBytesRead);

fileStream.Write(reciveBuffer, 0, bytesRead);
totalBytesRead += bytesRead;
fileStream.Write(reciveBuffer, 0, bytesRead);
totalBytesRead += bytesRead;

bytesInOneSecond += bytesRead;
bytesInOneSecond += bytesRead;

if (stopWatch.ElapsedMilliseconds >= 1000)
if (stopWatch.Elapsed.TotalSeconds >= 1)
{
unitsPerSecond = (int)(bytesInOneSecond * stopWatch.Elapsed.TotalSeconds);
if (unitsPerSecond > 125000)
{
unitsPerSecond = (unitsPerSecond + bytesInOneSecond) / 2;
if (unitsPerSecond > 125000)
{
unitsPerSecond /= 125000;
unit = "Mb";
}
else
{
unitsPerSecond /= 125;
unit = "Kb";
}
bytesInOneSecond = 0;
stopWatch.Restart();
unitsPerSecond /= 125000;
unit = "Mb";
}

ApiManager.SendMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] ");
else
{
unitsPerSecond /= 125;
unit = "Kb";
}
bytesInOneSecond = 0;
stopWatch.Restart();
}

fileStream.Close();
ApiManager.SendNotificationMessage($"\rDownloading: {Math.Clamp(Math.Ceiling(100d / fileSize * totalBytesRead), 0, 100)}% {totalBytesRead / 1000}/{fileSize / 1000}KB [{unitsPerSecond}{unit}/s] ");
}

if (totalBytesRead < fileSize)
{
continue;
}
fileStream.Close();

ApiManager.SendMessageNewLine(string.Empty);
if (totalBytesRead < fileSize)
{
continue;
}

ApiManager.SendMessageNewLine("Validating file...");
if (FileValidator.ValidateHash(filePath, hash))
{
_ = filesManager.TryAdd(filePath, out _, out _);
}
else
{
ApiManager.SendMessageNewLine("Warning: File hash does not match! File might me corrupted or manipulated!", NotificationMessageType.Warning);
}
ApiManager.SendNotificationMessageNewLine(string.Empty);

ApiManager.SendMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}");
ApiManager.SendMessageNewLine("Done", NotificationMessageType.Success);
stopWatch.Stop();
hostsManager.SaveHosts();
return;
ApiManager.SendNotificationMessageNewLine("Validating file...");
if (FileValidator.ValidateHash(filePath, hash))
{
_ = filesManager.TryAdd(filePath, out _, out _);
}
else
{
ApiManager.SendMessageNewLine(dataReceived, NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine("Warning: File hash does not match! File might me corrupted or manipulated! Trying next host...", NotificationMessageType.Warning);
continue;
}

ApiManager.SendNotificationMessageNewLine($"File saved at: {Path.GetFullPath(filePath)}");
ApiManager.SendNotificationMessageNewLine("Done", NotificationMessageType.Success);
stopWatch.Stop();
hostsManager.SaveHosts();
return;
}
ApiManager.SendMessageNewLine("None of the available hosts have the requested file!", NotificationMessageType.Error);
ApiManager.SendNotificationMessageNewLine("None of the available hosts have the requested file!", NotificationMessageType.Error);
hostsManager.SaveHosts();
}
}
Loading

0 comments on commit 9f08b5c

Please sign in to comment.