diff --git a/.idea/.idea.Elisa/.idea/.gitignore b/.idea/.idea.Elisa/.idea/.gitignore new file mode 100644 index 0000000..9dde89d --- /dev/null +++ b/.idea/.idea.Elisa/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/contentModel.xml +/modules.xml +/.idea.Elisa.iml +/projectSettingsUpdater.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.idea.Elisa/.idea/indexLayout.xml b/.idea/.idea.Elisa/.idea/indexLayout.xml new file mode 100644 index 0000000..7b08163 --- /dev/null +++ b/.idea/.idea.Elisa/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Elisa.WebAPI/Controllers/IndexController.cs b/Elisa.WebAPI/Controllers/IndexController.cs new file mode 100644 index 0000000..2d6d169 --- /dev/null +++ b/Elisa.WebAPI/Controllers/IndexController.cs @@ -0,0 +1,96 @@ +using System.Text; +using Elisa.WebAPI.Utils; +using Microsoft.AspNetCore.Mvc; +using Serilog; + +namespace Elisa.WebAPI.Controllers; + +public class IndexController : Controller +{ + string ClientVersion = 30400.ToString(); + string DataVersion = "d630eea53a1b869fa4d7d1479a3d09e7"; + string ABVersion = 2024051417.ToString(); + + [HttpPost("index.php", Name = "ServerList")] + public async Task ServerList([FromForm] IFormCollection req_id) + { + //Log all the values + foreach (var key in req_id.Keys) + { + Log.Information("{key} = {value}", key, req_id[key]); + //See if req_id has the value "newserverList" + if (req_id[key].Contains("newserverList")) + { + //Print out the current working directory + Log.Information("Current working directory: {0}", Directory.GetCurrentDirectory()); + //If it does, return the new serverlist.xml + var stream = System.IO.File.ReadAllText("Data\\serverlist.xml"); + + return Results.Text(stream, "text/html", Encoding.UTF8); + } + } + + //If it doesn't, return the default response + return Results.Json(new + { + now = DateTime.Now.ToUnixSeconds(), + tomorrow_zero = Time.GetTomorrowZero(), + month_zero = Time.GetCurrentMonthZero(), + next_month_zero = Time.GetNextMonthZero(), + timezone = "PST8PDT", + data_version = DataVersion, + client_version = ClientVersion, + ab_version = ABVersion, + is_kick = "0", + weekday = 1, + authentication_url = $"http://realauth.ucenter.ppgame.com/authoriz.html?appid={0}&openid={1}&accounttype=1&language=zh" + }); + } + [HttpGet("1001/index/version", Name = "Version")] + public async Task Version([FromQuery] string req_id) + { + //If it doesn't, return the default response + return Results.Json(new + { + now = DateTime.Now.ToUnixSeconds(), + tomorrow_zero = Time.GetTomorrowZero(), + month_zero = Time.GetCurrentMonthZero(), + next_month_zero = Time.GetNextMonthZero(), + timezone = "PST8PDT", + data_version = DataVersion, + client_version = ClientVersion, + ab_version = ABVersion, + is_kick = "0", + weekday = 1, + authentication_url = $"http://realauth.ucenter.ppgame.com/authoriz.html?appid={0}&openid={1}&accounttype=1&language=zh" + }); + } + + [HttpGet("image/imageconfig.txt", Name = "ImageConfig")] + public async Task ImageConfig([FromQuery] string req_id) + { + //If it doesn't, return the default response + return Results.Text(@"//类型名|是否会保存到本地|资源名 +//HotUpdateBackground|true|Background161101.png +HotUpdateBackground|true|1ff934568eb9d2a6_draw_221213175434.png +LoginBackground|true|201805 + +HomeBackground|true| +attendance1|true| +attendance2|true|d3d1b3e115da2221_draw_240507142255.jpg +CDKey2|true| +SevenSupply1|true|c30482012b01a83a_draw_181106004.png +FirstPurchase1|true|"); + } + + [Route("{*url}")] + public IActionResult HandleAll(string url) + { + // Log the incoming request + Serilog.Log.Information("Handling unmatched request for URL: {Url}", url); + + // Return a custom response + return Content($"Handled by catch-all route: {url}"); + } + +} \ No newline at end of file diff --git a/Elisa.WebAPI/Data/serverlist.xml b/Elisa.WebAPI/Data/serverlist.xml new file mode 100644 index 0000000..9838810 --- /dev/null +++ b/Elisa.WebAPI/Data/serverlist.xml @@ -0,0 +1,101 @@ + + + + + GRIFFIN + http://127.0.0.1/ + 1001 + 0 + 0 + 0 + 0 + 2024051417 + 1714705161 + 1 + + + + http://127.0.0.1/pages/notice + http://127.0.0.1/pages/update_url + 2018-05-16 20:00:43 + 2036-09-01 00:00:00 + 30400 + https://play.google.com/store/apps/details?id=com.sunborn.girlsfrontline.en + 20410 + + v.3.0400 Update Content: + + [Mobile Armor System Optimizations] + + 1. Optimized: The "Mobile Armor" combat results screen now shows the remaining HP and other such info of the Mobile Armor units in question. An option to "Armor Enhancement" has been added to the Mission Failed screen. + + 2. Optimized: If a Mobile Armor 4unit is not "In Combat", Fire Support Units assigned to the armor in question can be independently deployed as normal. + + 3. Optimized: The "Tech Tree" display of the Mobile Armor system now features a before and after display of effects when activating certain nodes. + + 4. Optimized: Mobile Armor support skills are now labelled with the [Support] tag. + + 5. Optimized: The Armor Design Shop's item preview function now adds an indication that an item is being previewed, as well as showing if a certain mobile armor design will clash with others. You can also instantly purchase a desired item after trying it out. Changing an armor's degisn blueprint no longer clears out equipped designs. + + The "Armor Design" set display mode has also been added. You may use this function to preview the look of a scerain set of armor designs as well as purchase it immediately. + + The "Armor Design" purchase screen has been made easier to use. + + The arrangement of items in the "Armor Design" blueprint display screen has been improved. + + 6. Optimized: Information display for non-generic components has been improved and the equip screen has been mae easier to use. + + 7. Optimized: Information display and filtering for generic components has been improved. + + + [Other New Content] + + 1. Added: "Armored Assault" mode in "Gray Zone Exploration" now has the "Sweep" function. If you have already cleared up to a certain point in the stage, you can click "Sweep" to expend attempts to directly obtain the stage rewards. + + 2. Added: The "Gray Zone Exploration" system now features a new Proxy Planning function. At the "Echelon Formation" or the "Gray Zone Exploration" difficulty select, you can click the newly-added "Echelon Pre-Select" button to enter the echelon pre-selection screen. + On this screen, you can edit and select echelons for use in Proxy Battle mode, as well as deciding whether the echelons in question will take part in day or night battles. + Once you have finished editing, selected and activated your pre-selected echelons, the system will only use these echelons or units during Proxy Battle mode. + + 3. Added: Combat Simulations now have the "Sweep" function. During "EXP Mode", "Data Mode", "Capsule Mode", "Neural Cloud Corridor" and "Coalition Drill, you can select the number of times you want to sweep the simulation in question and press the "Sweep" button to expend the corresponding amount of attempts and gain the appropriate materials as rewards. + + 4. Added: The "Echelon Formation" screen now has a Share function. By clicking the "Share" button, you can convert your current echelon's data into a bar code or QR code which can be shared with other Commanders. This code can be used by other Commanders to reproduce your echelon. + This function is not currently available for vehicle echelons. + + 5. Added: The "Search" function has ben aded to the unit display screen. You can enter keywords to search for units which meet the criteria. + + 6. Added: The "Favorite" function has been added to unit detail pages. By clicking it, you can favorite the unit in question, which enables the filter option "Only show favorited" units. + + 7. Added: The armor components "Vehicle Shotgun", "Mini Mortar", "Laser Rangefinder", "Camouflage Netting", "Top Slat Armor" can be obtained through exploring the "Vitrified - Hell" region during "Gray Zone Exploration". + + [Other Optimizations] + + 1. Optimized: The "Repair All " option now includes Fire Support Units and Mobile Armors. + + 2. Optimized: Mid-battle nformation display for Fire Support Units has been improved. You can view information on Fire Support Units and Mobile Armors units by clicking and holding on them. + + 3. Optimized: The post-mission reward display screen in Gray Zone Exploration has been tweaked. + + 4. Optimized: The overall functional experience of the Proxy Battle system in Gray Zone Exploration has been improved. + + 5. Optimized: The Chip Enhancement system for Fire Support Units has been improved. The Chip Enhancement screen now has options to "Max-Enhance One Chip" and "Max-Enhance Multiple Chips". + + 6. Optimized: Data display for "Equipment" has been improved. A special equipment buff tab has been added for the equipment detail display screen. + + 7. Optimized: The Echelon Formation screen now gives the option to select multiple echelons at once. Also, certain Fire Support Units selection screens allow you to select multiple Fire Support Units at once. + + 8. Optimized: The maximum amount of Surplus EXP that can be held at one time has been increased. Kalina's speed of writing combat reports has also been increased. + + 9. Optimized: Alerts have been added for the addition of new Career Missions. + + 10. Optimized: Unit selection displays have been improved. The option to select units based on their Repair, Move Speed and other stats has also been added. + + 11. Optimized: The potential dropped items display for missions ahas been improved. It now has popups for unlock conditions and the layout has been improved. + + 12. Optimized: Planning Mode AP expenditures now display extra APs for echelons and vehicle fuel supply status. + + 13. Optimized: A problem where one could not drag or shrink unit CGs when inspecting them in the Unit Details screen. + + 14. Optimized: A problem where the rewards screen would be displayed multiple times after certain Ranking Mode stages were made permanently available in the campaign tab. + + + diff --git a/Elisa.WebAPI/Elisa.WebAPI.csproj b/Elisa.WebAPI/Elisa.WebAPI.csproj new file mode 100644 index 0000000..63825e2 --- /dev/null +++ b/Elisa.WebAPI/Elisa.WebAPI.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + + Always + + + + diff --git a/Elisa.WebAPI/Program.cs b/Elisa.WebAPI/Program.cs new file mode 100644 index 0000000..0253402 --- /dev/null +++ b/Elisa.WebAPI/Program.cs @@ -0,0 +1,53 @@ +using System.Reflection; +using System.Text.Encodings.Web; +using Elisa.WebAPI.Services; +using Serilog; + +string ClientVersion = 30400.ToString(); +string DataVersion = "d630eea53a1b869fa4d7d1479a3d09e7"; +string ABVersion = 2024051417.ToString(); + + +var builder = WebApplication.CreateBuilder(args); +builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration)); +builder.Services.AddHttpClient(); + +// Add services to the container. + +builder.Services.AddControllers() + .AddJsonOptions(options => + { + options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; + + }); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); +builder.Services.AddHostedService(provider => + new ProxyBackgroundService("127.0.0.1")); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} +app.UseSerilogRequestLogging(); + +//app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +Log.Information($"Version {Assembly.GetEntryAssembly()?.GetCustomAttribute()?.InformationalVersion}"); +Log.Information($"Client Version: {ClientVersion}"); +Log.Information($"Data Version: {DataVersion}"); +Log.Information($"AB Version: {ABVersion}"); +Log.Information($"Starting {Assembly.GetEntryAssembly()?.GetName().Name}..."); + + + +app.Run(); \ No newline at end of file diff --git a/Elisa.WebAPI/Properties/launchSettings.json b/Elisa.WebAPI/Properties/launchSettings.json new file mode 100644 index 0000000..edc61ef --- /dev/null +++ b/Elisa.WebAPI/Properties/launchSettings.json @@ -0,0 +1,40 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:3505", + "sslPort": 44376 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "launchUrl": "swagger", + "applicationUrl": "http://127.0.0.1", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7010;http://localhost:5208", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Elisa.WebAPI/ProxyControl.cs b/Elisa.WebAPI/ProxyControl.cs new file mode 100644 index 0000000..31f8bae --- /dev/null +++ b/Elisa.WebAPI/ProxyControl.cs @@ -0,0 +1,63 @@ +using System; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Titanium.Web.Proxy; +using Titanium.Web.Proxy.EventArguments; +using Titanium.Web.Proxy.Models; + +namespace Elisa.WebAPI; + +public class ProxyControl +{ + private static readonly Regex HostFilter = new Regex("(.*).(girlfrontline\\.co\\.kr|ppgame\\.com|txwy\\.tw|sunborngame\\.com|aihelp.net.cn).*"); + private readonly string forwardIpAddress; + private readonly ProxyServer proxyServer; + private readonly ExplicitProxyEndPoint explicitEndPoint; + + public ProxyControl(string forwardIpAddress, int port = 8888) + { + this.forwardIpAddress = forwardIpAddress; + proxyServer = new ProxyServer(); + explicitEndPoint = new ExplicitProxyEndPoint(System.Net.IPAddress.Any, port, true); + + proxyServer.BeforeRequest += OnRequest; + + } + + public void Start() + { + proxyServer.AddEndPoint(explicitEndPoint); + proxyServer.Start(); + + proxyServer.SetAsSystemHttpProxy(explicitEndPoint); + proxyServer.SetAsSystemHttpsProxy(explicitEndPoint); + } + + public void Stop() + { + proxyServer.BeforeRequest -= OnRequest; + proxyServer.Stop(); + + } + + private async Task OnRequest(object sender, SessionEventArgs e) + { + var requestUri = e.HttpClient.Request.RequestUri; + if (HostFilter.IsMatch(requestUri.Host)) + { + //Log the request and where its forwarding to + Serilog.Log.Information("Forwarding request for {RequestUri} to {ForwardIpAddress}", requestUri, forwardIpAddress); + + //Build an entirely new URI with the specified IP address + var newUri = new Uri("http://" + forwardIpAddress + requestUri.PathAndQuery, UriKind.Absolute); + + Serilog.Log.Information("Forwarded request to {requestUri}", newUri); + + e.HttpClient.Request.RequestUri = newUri; + + //Bubble it out to user + + } + } + +} \ No newline at end of file diff --git a/Elisa.WebAPI/Services/ProxyBackgroundService.cs b/Elisa.WebAPI/Services/ProxyBackgroundService.cs new file mode 100644 index 0000000..cd249af --- /dev/null +++ b/Elisa.WebAPI/Services/ProxyBackgroundService.cs @@ -0,0 +1,32 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; + +namespace Elisa.WebAPI.Services; + +public class ProxyBackgroundService : BackgroundService +{ + private readonly ProxyControl _proxyControl; + + public ProxyBackgroundService(string forwardIpAddress) + { + _proxyControl = new ProxyControl(forwardIpAddress); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _proxyControl.Start(); + stoppingToken.Register(() => _proxyControl.Stop()); + + // Keep the background service running + while (!stoppingToken.IsCancellationRequested) + { + await Task.Delay(1000, stoppingToken); + } + } + + public override async Task StopAsync(CancellationToken stoppingToken) + { + await base.StopAsync(stoppingToken); + } +} diff --git a/Elisa.WebAPI/Utils/Crypto.cs b/Elisa.WebAPI/Utils/Crypto.cs new file mode 100644 index 0000000..46d27d4 --- /dev/null +++ b/Elisa.WebAPI/Utils/Crypto.cs @@ -0,0 +1,253 @@ +using ICSharpCode.SharpZipLib.GZip; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; + +namespace Elisa.WebAPI.Utils; + +public static class Crypto +{ + static DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + static MD5 md5 = System.Security.Cryptography.MD5.Create(); + + public static string Decrypt(string body, string key) + { + if (string.IsNullOrEmpty(body) || string.IsNullOrEmpty(key)) + return string.Empty; + + if (body.Length == 1 || body.StartsWith("error:") || (body.StartsWith("{") && body.EndsWith("}"))) + return body; + + try + { + string text = MD5(MD5(key).Substring(16)); + string pwd = text + MD5(text); + + if (body.StartsWith("#")) + { + body = body.Substring(1); + + return GZipDecompress(RC4(ConvertFromBase64String(body), pwd).Skip(26).ToArray()); + } + + byte[] bytes = RC4(ConvertFromBase64String(body), pwd); + string @string = Encoding.UTF8.GetString(bytes); + + return (@string.Length > 26) ? @string.Substring(26) : string.Empty; + } + catch + { + } + + return string.Empty; + } + + public static string Encrypt(string body, string key) + { + try + { + byte[] array = GZipCompress(Encoding.UTF8.GetBytes(body)); + string text = MD5(key); + string s = MD5(text.Substring(0, 16)); + string text2 = MD5(text.Substring(16, 16)); + string pwd = text2 + MD5(text2); + byte[] bytes = Encoding.UTF8.GetBytes(string.Format("{0}", Math.Round(GetCurrentSec()) + 3600.0)); + string s2 = MD5(array.Concat(Encoding.UTF8.GetBytes(s)).ToArray()).Substring(0, 16); + byte[] array2 = new byte[array.Length + 26]; + + Array.Copy(bytes, 0, array2, 0, bytes.Length); + Array.Copy(Encoding.UTF8.GetBytes(s2), 0, array2, 10, 16); + Array.Copy(array, 0, array2, 26, array.Length); + + return "#" + Convert.ToBase64String(RC4(array2, pwd)); + } + catch + { + } + + return string.Empty; + } + + public static byte[] ConvertFromBase64String(string input) + { + byte[] result = []; + + try + { + result = Convert.FromBase64String(input); + } + catch + { + try + { + result = Convert.FromBase64String(input + "="); + } + catch + { + try + { + result = Convert.FromBase64String(input + "=="); + } + catch + { + return result; + } + } + } + + return result; + } + + public static double GetCurrentSec() + { + return (DateTime.UtcNow - epoch).TotalSeconds; + } + + public static string MD5(string input) + { + return MD5(Encoding.UTF8.GetBytes(input)); + } + + public static string MD5(byte[] input) + { + byte[] array = md5.ComputeHash(input); + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < array.Length; i++) + stringBuilder.Append(array[i].ToString("x2")); + + return stringBuilder.ToString(); + } + + public static byte[] RC4(byte[] data, string pwd) + { + return RC4(data, Encoding.UTF8.GetBytes(pwd)); + } + + public static byte[] RC4(byte[] data, byte[] pwd) + { + int[] array = new int[256]; + int[] array2 = new int[256]; + byte[] array3 = new byte[data.Length]; + int i; + int num; + + for (i = 0; i < 256; i++) + { + array[i] = (int)pwd[i % pwd.Length]; + array2[i] = i; + } + + for (i = (num = 0); i < 256; i++) + { + int num2 = array2[i]; + + num = (num + array2[i] + array[i]) % 256; + array2[i] = array2[num]; + array2[num] = num2; + } + + int num3; + num = (num3 = (i = 0)); + + while (i < data.Length) + { + num3++; + num3 %= 256; + num += array2[num3]; + num %= 256; + + int num2 = array2[num3]; + array2[num3] = array2[num]; + array2[num] = num2; + + int num4 = array2[(array2[num3] + array2[num]) % 256]; + array3[i] = (byte)((int)data[i] ^ num4); + + i++; + } + + return array3; + } + + public static byte[] GZipCompress(byte[] raw) + { + byte[] result; + + using (MemoryStream memoryStream = new MemoryStream()) + { + using GZipOutputStream gzipOutputStream = new GZipOutputStream(memoryStream); + + gzipOutputStream.IsStreamOwner = false; + gzipOutputStream.Write(raw, 0, raw.Length); + gzipOutputStream.Flush(); + gzipOutputStream.Finish(); + + result = memoryStream.ToArray(); + } + + return result; + } + + public static string GZipDecompress(byte[] raw) + { + string result; + + using (MemoryStream memoryStream = new MemoryStream(raw)) + { + using Stream stream = new GZipInputStream(memoryStream); + using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); + + result = streamReader.ReadToEnd(); + } + + return result; + } + + public static string CompressText(string text) + { + byte[] bytes = Encoding.UTF8.GetBytes(text); + byte[]? inArray = null; + + using (MemoryStream memoryStream = new MemoryStream()) + { + using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress)) + { + gzipStream.Write(bytes, 0, bytes.Length); + } + + inArray = memoryStream.ToArray(); + } + + return Convert.ToBase64String(inArray); + } + + public static string DecompressText(string text) + { + string result = string.Empty; + + using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(text))) + { + using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) + { + using (StreamReader streamReader = new StreamReader(gzipStream)) + { + result = streamReader.ReadToEnd(); + } + } + } + + return result; + } + + public static string ConvertMD5(string input) + { + byte[] array = md5.ComputeHash(Encoding.UTF8.GetBytes(input)); + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < array.Length; i++) + stringBuilder.Append(array[i].ToString("x2")); + + return stringBuilder.ToString(); + } +} diff --git a/Elisa.WebAPI/Utils/RNG.cs b/Elisa.WebAPI/Utils/RNG.cs new file mode 100644 index 0000000..5b55efc --- /dev/null +++ b/Elisa.WebAPI/Utils/RNG.cs @@ -0,0 +1,36 @@ +namespace Elisa.WebAPI.Utils; + +public static class RNG +{ + static readonly Random random = new Random((int)DateTime.Now.Ticks); + + public static int Next(int min, int max) + => random.Next(min, max); + + public static int Next(int max) + => random.Next(max); + + public static float NextFloat(float min, float max) + { + double range = (double)max - min; + double sample = random.NextDouble(); + double scaled = (sample * range) + min; + + return (float)scaled; + } + + public static float NextFloat(float max) + => NextFloat(0f, max); + + public static bool NextBool() + => random.Next(2) == 0; + + public static float NextRoll() + => NextFloat(100f); + + public static T NextFromList(IList list) + => list[random.Next(list.Count)]; + + public static U NextFromDict(IDictionary dict) + => dict.ElementAt(random.Next(dict.Count)).Value; +} diff --git a/Elisa.WebAPI/Utils/Singleton.cs b/Elisa.WebAPI/Utils/Singleton.cs new file mode 100644 index 0000000..305d377 --- /dev/null +++ b/Elisa.WebAPI/Utils/Singleton.cs @@ -0,0 +1,17 @@ +namespace Elisa.WebAPI.Utils; + +public abstract class Singleton where T : new() +{ + static T instance; + public static T Instance + { + get + { + if (instance == null) + instance = new T(); + + return instance; + } + set => instance = value; + } +} diff --git a/Elisa.WebAPI/Utils/Time.cs b/Elisa.WebAPI/Utils/Time.cs new file mode 100644 index 0000000..77fdb8c --- /dev/null +++ b/Elisa.WebAPI/Utils/Time.cs @@ -0,0 +1,19 @@ +namespace Elisa.WebAPI.Utils; + +public static class Time +{ + public static long GetTomorrowZero() + => new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, DateTimeKind.Utc).AddDays(1).ToUnixSeconds(); + + public static long GetCurrentMonthZero() + => new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0, DateTimeKind.Utc).ToUnixSeconds(); + + public static long GetNextMonthZero() + => new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).ToUnixSeconds(); +} + +internal static class DateTimeExtensions +{ + public static long ToUnixSeconds(this DateTime dateTime) + => (long)(dateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; +} diff --git a/Elisa.WebAPI/appsettings.Development.json b/Elisa.WebAPI/appsettings.Development.json new file mode 100644 index 0000000..52c6844 --- /dev/null +++ b/Elisa.WebAPI/appsettings.Development.json @@ -0,0 +1,39 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Information" + } + }, + "AllowedHosts": "*", + "Serilog": { + "Using": ["Serilog", "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Async"], + "MinimumLevel": { + "Default": "Debug", + "Override": { + "Microsoft": "Information", + "System": "Information" + } + }, + "WriteTo": [ + { + "Name": "Async", + "Args": { + "configure": [ + { + "Name": "Console" + }, + { + "Name": "File", + "Args": { + "path": "Logs/log-.txt", + "rollingInterval": "Day" + } + } + ] + } + } + ], + "Enrich": ["FromLogContext", "WithThreadId", "WithMemoryUsage"] + } +} \ No newline at end of file diff --git a/Elisa.WebAPI/appsettings.json b/Elisa.WebAPI/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/Elisa.WebAPI/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Elisa.sln b/Elisa.sln index d590b6a..46b1bab 100644 --- a/Elisa.sln +++ b/Elisa.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 17.8.34316.72 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elisa", "Elisa\Elisa.csproj", "{AE240F77-1DA8-42B0-9D81-E42B8E7B7D77}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elisa.WebAPI", "Elisa.WebAPI\Elisa.WebAPI.csproj", "{926559D5-FF03-4D79-9475-3F187BB73E49}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {AE240F77-1DA8-42B0-9D81-E42B8E7B7D77}.Debug|Any CPU.Build.0 = Debug|Any CPU {AE240F77-1DA8-42B0-9D81-E42B8E7B7D77}.Release|Any CPU.ActiveCfg = Release|Any CPU {AE240F77-1DA8-42B0-9D81-E42B8E7B7D77}.Release|Any CPU.Build.0 = Release|Any CPU + {926559D5-FF03-4D79-9475-3F187BB73E49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {926559D5-FF03-4D79-9475-3F187BB73E49}.Debug|Any CPU.Build.0 = Debug|Any CPU + {926559D5-FF03-4D79-9475-3F187BB73E49}.Release|Any CPU.ActiveCfg = Release|Any CPU + {926559D5-FF03-4D79-9475-3F187BB73E49}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Elisa/Elisa.csproj b/Elisa/Elisa.csproj index b9ec5df..ea78690 100644 --- a/Elisa/Elisa.csproj +++ b/Elisa/Elisa.csproj @@ -33,6 +33,7 @@ + diff --git a/Elisa/Program.cs b/Elisa/Program.cs index 538c744..05ca63f 100644 --- a/Elisa/Program.cs +++ b/Elisa/Program.cs @@ -38,7 +38,15 @@ internal static class Program Task.Run(InputSystem.Start); Task.Run(Proxy.Start); + //var forwardIpAddress = "10.0.0.8:10800"; // Replace with the desired IP address + //var proxyControl = new ProxyControl(forwardIpAddress); + + //proxyControl.Start(); + Task.Run(GameServer.Start).Wait(); + + Log.Information("Shutting down..."); + //proxyControl.Stop(); } private static void SetupConfig() diff --git a/Elisa/Proxy.cs b/Elisa/Proxy.cs index a2a6987..40ee49b 100644 --- a/Elisa/Proxy.cs +++ b/Elisa/Proxy.cs @@ -26,7 +26,7 @@ public static class Proxy using (TcpClient server = new TcpClient()) { - await server.ConnectAsync(serverUrl, 80); + await server.ConnectAsync(serverUrl, 10800); Log.Information($"Proxy: Connected to Elisa"); using (NetworkStream clientStream = client.GetStream()) diff --git a/Elisa/ProxyControl.cs b/Elisa/ProxyControl.cs new file mode 100644 index 0000000..ed24c23 --- /dev/null +++ b/Elisa/ProxyControl.cs @@ -0,0 +1,65 @@ +using System; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Titanium.Web.Proxy; +using Titanium.Web.Proxy.EventArguments; +using Titanium.Web.Proxy.Models; + +namespace Elisa; + +public class ProxyControl +{ + private static readonly Regex HostFilter = new Regex("(gf-|gfjp-).*(girlfrontline\\.co\\.kr|ppgame\\.com|txwy\\.tw|sunborngame\\.com).*"); + private readonly string forwardIpAddress; + private readonly ProxyServer proxyServer; + private readonly ExplicitProxyEndPoint explicitEndPoint; + + public ProxyControl(string forwardIpAddress, int port = 9000) + { + this.forwardIpAddress = forwardIpAddress; + proxyServer = new ProxyServer(); + explicitEndPoint = new ExplicitProxyEndPoint(System.Net.IPAddress.Any, port, true); + + proxyServer.BeforeRequest += OnRequest; + + } + + public async Task Start() + { + proxyServer.AddEndPoint(explicitEndPoint); + proxyServer.Start(); + + proxyServer.SetAsSystemHttpProxy(explicitEndPoint); + proxyServer.SetAsSystemHttpsProxy(explicitEndPoint); + + + Console.WriteLine("Proxy server started. Press any key to stop."); + Console.ReadKey(); + await Task.Delay(-1); + + } + + public void Stop() + { + proxyServer.BeforeRequest -= OnRequest; + proxyServer.Stop(); + } + + private async Task OnRequest(object sender, SessionEventArgs e) + { + var requestUri = e.HttpClient.Request.RequestUri; + if (HostFilter.IsMatch(requestUri.Host)) + { + //Log the request and where its forwarding to + Serilog.Log.Information("Forwarding request to {forwardIpAddress} for {requestUri}", forwardIpAddress, requestUri); + //Forward the request to the specified IP address + var newUri = new UriBuilder(requestUri) + { + Host = forwardIpAddress + }.Uri; + + e.HttpClient.Request.RequestUri = newUri; + } + } + +} \ No newline at end of file diff --git a/Elisa/appsettings.json b/Elisa/appsettings.json index ebff94b..f2a955e 100644 --- a/Elisa/appsettings.json +++ b/Elisa/appsettings.json @@ -2,7 +2,7 @@ "Kestrel": { "EndPoints": { "Http": { - "Url": "http://0.0.0.0:80" + "Url": "http://0.0.0.0:10800" } } },