Files
Crimson--Vanadium--backend/Program.cs
b016488d-939a-4910-a596-93b77fc9ab9c 06d03bd65e njcw5kgsAEy-LEoXmiN5Vg
2026-07-24 14:58:44 +00:00

191 lines
7.3 KiB
C#

using System.Runtime.InteropServices;
using Microsoft.AspNetCore.HttpOverrides;
using System.Linq;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Http.Features;
using sscs2023.Classes.DBs;
using sscs2023.Controllers;
using sscs2023.Hubs;
using sscs2023.Utils.NotiController;
using sscs2023.Services;
using System.Collections.Concurrent;
using System.Net.WebSockets;
namespace sscs2023
{
public class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
public static string dataDir = Path.Join(Environment.CurrentDirectory, "Data");
public static ConcurrentDictionary<string, long> PendingConnections = new();
public static ConcurrentDictionary<long, WebSocket> ActiveSockets = new();
public static async Task Main(string[] args)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var handle = GetStdHandle(-11);
SetConsoleMode(handle, 0x0001 | 0x0002 | 0x0004);
}
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.AspNetCore.Routing", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.AspNetCore.Mvc", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting", LogLevel.Warning);
if (!Directory.Exists(dataDir))
{
Console.WriteLine("Setting up data directory...");
string[] foldersToCreate =
{
dataDir,
Path.Join(dataDir, "Images"),
Path.Join(dataDir, "Images", "PlayerImages"),
Path.Join(dataDir, "Images", "PolaroidImages"),
Path.Join(dataDir, "CDN", "DataBlobs"),
Path.Join(dataDir, "CDN", "InventionBlobs"),
Path.Join(dataDir, "CDN", "RoomBlobs"),
Path.Join(dataDir, "Imports"),
Path.Join(dataDir, "DBs")
};
foreach (var folder in foldersToCreate)
Directory.CreateDirectory(folder);
Console.WriteLine($"Data directory created at {dataDir}");
}
builder.Services.Configure<FormOptions>(o =>
{
o.MultipartBodyLengthLimit = 10_000_000;
});
builder.Services.AddControllers().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
});
builder.Services.AddHttpClient();
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.All;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
builder.Services.AddSignalR(options =>
{
options.KeepAliveInterval = TimeSpan.FromSeconds(10);
options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
options.MaximumReceiveMessageSize = 1_048_576;
options.EnableDetailedErrors = true;
});
builder.Services.AddSingleton<IUserIdProvider, PlayerIdProvider>();
builder.Services.AddSingleton<NotificationService>();
builder.Services.AddHostedService<DiscordBotService>();
var app = builder.Build();
var notiService = app.Services.GetRequiredService<NotificationService>();
NotificationsController.Init(notiService);
DiscordBotController.Init(notiService);
app.Use(async (context, next) =>
{
await next();
string timeStr = DateTime.UtcNow.ToString("HH:mm:ss");
string timePart = $"\u001b[91m[{timeStr}]\u001b[0m";
string method = context.Request.Method.ToUpper();
string methodColor = "\u001b[37m";
if (method == "GET")
methodColor = "\u001b[32m";
else if (method == "POST" || method == "PUT")
methodColor = "\u001b[33m";
else if (method == "DELETE")
methodColor = "\u001b[31m";
string methodPart = $"{methodColor}{method}\u001b[0m";
string fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
string urlPart = $"\u001b[37m{fullUrl}\u001b[0m";
int statusCode = context.Response.StatusCode;
string statusColor = "\u001b[37m";
if (statusCode >= 100 && statusCode < 200)
statusColor = "\u001b[33m";
else if (statusCode >= 200 && statusCode < 300)
statusColor = "\u001b[32m";
else if (statusCode >= 400)
statusColor = "\u001b[31m";
string statusPart = $"{statusColor}{statusCode}\u001b[0m";
string ip = context.Request.Headers["CF-Connecting-IP"].FirstOrDefault()
?? context.Connection.RemoteIpAddress?.ToString()
?? "Unknown";
string ipPart = $"\u001b[38;5;208m[{ip}]\u001b[0m";
Console.WriteLine($"{timePart} {ipPart} {methodPart}: {urlPart} {statusPart}");
});
app.UseForwardedHeaders();
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(30)
});
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/noti/hub/v1") &&
!context.Request.Path.Value!.Contains("negotiate") &&
context.WebSockets.IsWebSocketRequest)
{
var connectionId = context.Request.Query["id"].ToString();
if (!Program.PendingConnections.TryRemove(connectionId, out var playerId))
{
context.Response.StatusCode = 401;
return;
}
var ws = await context.WebSockets.AcceptWebSocketAsync();
await NotificationsController.HandleConnectionAsync(playerId, ws);
return;
}
await next();
});
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
var adminPlayer = PlayerDB.Players.FindById(1);
if (adminPlayer?.Player != null)
{
adminPlayer.Player.Level = 99;
adminPlayer.Player.XP = PlayerDB.GetXPForLevel(99);
PlayerDB.Players.Update(adminPlayer);
}
DiscordBotService.Init(notiService);
sscs2023.Cloudflare.StartCloudflared();
app.Run("http://localhost:2059");
}
}
}