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