Files
HyperbolicDownloader/HyperbolicDownloaderApi/Commands/DownloadCommands.cs
T
Stone_Red a90af811c1 Fix important bug
- Fixed a bug that caused the content of the file to be sent as the filename
2022-02-28 20:28:05 +01:00

234 lines
8.0 KiB
C#

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, 1000);
}
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
{
ApiManager.SendMessageNewLine(dataReceived, NotificationMessageType.Error);
continue;
}
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;
}
ApiManager.SendMessageNewLine("None of the available hosts have the requested file!", NotificationMessageType.Error);
hostsManager.SaveHosts();
}
}