Added compression

This commit is contained in:
cxxpxr 2021-04-03 22:49:38 -04:00 committed by GitHub
parent 51cd792089
commit c5d2220b76
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 167 additions and 95 deletions

View file

@ -0,0 +1,60 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace LightReflectiveMirror.Compression
{
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string Compress(this string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <returns></returns>
public static string Decompress(this string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
}

View file

@ -1,90 +1,101 @@
using Grapevine; using Grapevine;
using Microsoft.Extensions.Configuration; using LightReflectiveMirror.Compression;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json; using Microsoft.Extensions.Logging;
using System; using Newtonsoft.Json;
using System.Threading.Tasks; using System;
using System.Collections.Generic;
namespace LightReflectiveMirror.Endpoints using System.Threading.Tasks;
{
[Serializable] namespace LightReflectiveMirror.Endpoints
struct RelayStats {
{ [Serializable]
public int ConnectedClients; struct RelayStats
public int RoomCount; {
public int PublicRoomCount; public int ConnectedClients;
public TimeSpan Uptime; public int RoomCount;
} public int PublicRoomCount;
public TimeSpan Uptime;
[RestResource] }
public class Endpoint
{ [RestResource]
[RestRoute("Get", "/api/stats")] public class Endpoint
public async Task Stats(IHttpContext context) {
{ private List<Room> _rooms { get => Program.instance.GetRooms(); }
RelayStats stats = new RelayStats
{ private RelayStats _stats { get => new RelayStats
ConnectedClients = Program.instance.GetConnections(), {
RoomCount = Program.instance.GetRooms().Count, ConnectedClients = Program.instance.GetConnections(),
PublicRoomCount = Program.instance.GetPublicRoomCount(), RoomCount = Program.instance.GetRooms().Count,
Uptime = Program.instance.GetUptime() PublicRoomCount = Program.instance.GetPublicRoomCount(),
}; Uptime = Program.instance.GetUptime()
}; }
string json = JsonConvert.SerializeObject(stats, Formatting.Indented);
await context.Response.SendResponseAsync(json); [RestRoute("Get", "/api/stats")]
} public async Task Stats(IHttpContext context)
{
[RestRoute("Get", "/api/servers")] string json = JsonConvert.SerializeObject(_stats, Formatting.Indented);
public async Task ServerList(IHttpContext context) await context.Response.SendResponseAsync(json);
{ }
if (Program.conf.EndpointServerList)
{ [RestRoute("Get", "/api/servers")]
string json = JsonConvert.SerializeObject(Program.instance.GetRooms(), Formatting.Indented); public async Task ServerList(IHttpContext context)
await context.Response.SendResponseAsync(json); {
} if (Program.conf.EndpointServerList)
else {
{ string json = JsonConvert.SerializeObject(_rooms, Formatting.Indented);
await context.Response.SendResponseAsync("Access Denied"); await context.Response.SendResponseAsync(json);
} }
} else
} await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
}
public class EndpointServer
{ [RestRoute("Get", "/api/compressed/servers")]
public bool Start(ushort port = 8080) public async Task ServerListCompressed(IHttpContext context)
{ {
try if (Program.conf.EndpointServerList)
{ {
var config = new ConfigurationBuilder() string json = JsonConvert.SerializeObject(_rooms);
.SetBasePath(System.IO.Directory.GetCurrentDirectory()) await context.Response.SendResponseAsync(json.Compress());
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) }
.Build(); else
await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
Action<IServiceCollection> configServices = (services) => }
{ }
services.AddLogging(configure => configure.AddConsole());
services.Configure<LoggerFilterOptions>(options => options.MinLevel = LogLevel.None); public class EndpointServer
}; {
public bool Start(ushort port = 8080)
Action<IRestServer> configServer = (server) => {
{ try
server.Prefixes.Add($"http://*:{port}/"); {
}; var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
var server = new RestServerBuilder(new ServiceCollection(), config, configServices, configServer).Build(); .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
server.Router.Options.SendExceptionMessages = false; .Build();
server.Start(); var server = new RestServerBuilder(new ServiceCollection(), config,
(services) =>
return true; {
} services.AddLogging(configure => configure.AddConsole());
catch services.Configure<LoggerFilterOptions>(options => options.MinLevel = LogLevel.None);
{ }, (server) =>
return false; {
} server.Prefixes.Add($"http://*:{port}/");
}).Build();
}
} server.Router.Options.SendExceptionMessages = false;
} server.Start();
return true;
}
catch
{
return false;
}
}
}
}

View file

@ -163,15 +163,16 @@ namespace LightReflectiveMirror
try try
{ {
natThread.Start(); natThread.Start();
}catch(Exception err) }
catch(Exception e)
{ {
WriteLogMessage("FAILED\n" + err, ConsoleColor.DarkRed); WriteLogMessage("FAILED\n" + e, ConsoleColor.DarkRed);
} }
} }
catch(Exception error) catch(Exception e)
{ {
WriteLogMessage("FAILED\nCheck if port is in use.", ConsoleColor.DarkRed, true); WriteLogMessage("FAILED\nCheck if port is in use.", ConsoleColor.DarkRed, true);
Console.WriteLine(error); Console.WriteLine(e);
} }
} }
} }
@ -285,7 +286,7 @@ namespace LightReflectiveMirror
string load = $"Chimp Event Listener Initializing... OK" + string load = $"Chimp Event Listener Initializing... OK" +
"\nHarambe Memorial Initializing... OK" + "\nHarambe Memorial Initializing... OK" +
"\nBananas initializing... OK\n"; "\nBananas Initializing... OK\n";
WriteLogMessage(t, ConsoleColor.Green); WriteLogMessage(t, ConsoleColor.Green);
WriteLogMessage(load, ConsoleColor.Cyan); WriteLogMessage(load, ConsoleColor.Cyan);