XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
using XFEWarframe.Core.Services;

namespace XFEWarframe.Core;

public sealed record RequestLog(long Id, DateTimeOffset Time, string Method, string Path, int Status, double DurationMs);

public sealed class GameEngine
{
    private readonly StateStore store;
    private readonly ServerOptions options;
    private readonly TimeProvider clock;
    private readonly Accounts accounts;
    private readonly PlayerPortal portal;
    private readonly IGoogleIdentityProvider google;
    private readonly PlayerApi player;
    private readonly SocialApi social;
    private readonly Sessions sessions;
    private readonly ProgressApi progress;
    private readonly StatsApi stats;
    private readonly Lazy<ItemCatalog> items = new(() => new());
    private readonly ConcurrentQueue<RequestLog> logs = new();
    private readonly DateTimeOffset started;
    private long totalRequests, failedRequests;
    private volatile bool maintenance;
    public RouteCatalog Routes { get; } = new();
    public OfficialEventSynchronizer OfficialEventSync { get; }
    public event Action<RequestLog>? RequestCompleted;
    public event Action? ShutdownRequested;
    public GameEngine(StateStore store, ServerOptions options, TimeProvider? time = null, IGoogleIdentityProvider? googleIdentityProvider = null, HttpClient? officialEventsClient = null)
    {
        this.store = store; this.options = options; clock = time ?? TimeProvider.System;
        google = googleIdentityProvider ?? new GoogleIdentityProvider(options);
        accounts = new(options, clock); player = new(clock); sessions = new(clock); progress = new(clock); stats = new(clock); social = new(clock); started = clock.GetUtcNow();
        portal = new(store, options, clock, accounts, () => items.Value);
        OfficialEventSync = new(store, options, clock, officialEventsClient);
    }
    public async Task<ApiResponse> Handle(ApiRequest request)
    {
        var timer = Stopwatch.StartNew(); ApiResponse response;
        try
        {
            if (request.Path.StartsWith("/control/", StringComparison.Ordinal)) response = await Control(request);
            else if (request.Path.StartsWith("/player/", StringComparison.Ordinal)) response = await portal.Handle(request, maintenance);
            else if (request.Path == "/health") response = request.Method == "GET" ? await store.Project(s => ApiResponse.Json(ServerIdentity.Health(s, options, maintenance))) : ApiResponse.Json(new { error = "Method not allowed" }, 405);
            else if (request.Path == "/" || request.Path.StartsWith("/webui", StringComparison.Ordinal)) response = ApiResponse.Json(new { error = "Not found", interfaceType = "WinUI 3" }, 404);
            else
            {
                if (maintenance) throw new ApiException(503, "Game API is in maintenance mode");
                var route = Routes.Resolve(request.Method, request.Path);
                if (route is null) throw new ApiException(Routes.All.Any(x => x.Path == request.Path) ? 405 : 404, "Route not found for this HTTP method");
                if (route.Status == "pending") throw new ApiException(501, $"C# migration pending: {route.Controller}");
                GoogleIdentity? identity = null;
                if (route.Controller == "signupAndroidController") identity = await google.Verify(request.Q("googleTokenId") ?? "");
                else if (route.Controller == "loginController" && request.ObjectBody().Value<string>("ClientType") == "Android") identity = await google.Verify(request.ObjectBody().Value<string>("GoogleTokenId") ?? "");
                response = route.Controller == "publicExportController" ? new PublicExportApi(items.Value).Handle(request)
                    : route.Controller is "contentCache" or "publicExportTexture" ? await new ContentApi(options).Handle(route.Controller, request)
                    : await store.Update(state => Execute(state, route.Controller, request, identity));
            }
        }
        catch (ApiException ex) { response = ApiResponse.Json(new { error = ex.Message }, ex.Status); }
        catch (Exception ex) when (ex is JsonException or FormatException or OverflowException or InvalidCastException or ArgumentException)
        { response = ApiResponse.Json(new { error = "Invalid request data" }, 400); }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Request failure ({ex.GetType().Name}): {ex.Message}");
            response = ApiResponse.Json(new { error = "Internal server error; see console log" }, 500);
        }
        var id = Interlocked.Increment(ref totalRequests);
        if (response.Status >= 400) Interlocked.Increment(ref failedRequests);
        var log = new RequestLog(id, clock.GetUtcNow(), request.Method, request.Path, response.Status, Math.Round(timer.Elapsed.TotalMilliseconds, 2));
        logs.Enqueue(log); while (logs.Count > 500) logs.TryDequeue(out _);
        try { RequestCompleted?.Invoke(log); }
        catch (Exception ex) { Console.Error.WriteLine($"Request log could not be written: {ex.Message}"); }
        return response;
    }
    private ApiResponse Execute(JObject state, string controller, ApiRequest request, GoogleIdentity? identity = null)
    {
        if (controller == "versionController") return ApiResponse.Text(request.Q("buildLabel")?.Replace(' ', '+') ?? options.FallbackBuildLabel);
        if (controller == "loginController")
        {
            var response = accounts.Login(state, request, identity);
            if (response.Status == 200)
            {
                var signedIn = Find(state, JObject.Parse(response.Body).RequiredString("id"));
                if (signedIn.Value<bool?>("SkipTutorial") ?? state.Obj("config").Value<bool>("skipTutorial")) TutorialProgress.Apply(signedIn, items.Value, clock);
            }
            return response;
        }
        if (controller == "signupAndroidController") return Accounts.SignupAndroid(state, request, identity!);
        if (ArbiterApi.Controllers.Contains(controller)) return new ArbiterApi(options).Handle(controller, state, request);
        if (CustomApi.PublicControllers.Contains(controller)) return new CustomApi(items.Value, clock, options).Handle(controller, state, null, request);
        if (controller == "getGuildAdsController" || controller == "customObstacleCourseLeaderboardController" && request.Q("act") == "f") return new GuildExtrasApi(clock).Handle(controller, state, null, request);
        if (VendorApi.Controllers.Contains(controller))
        {
            var current = request.Q("accountId") is null ? null : accounts.Authenticate(state, request);
            return new VendorApi(clock).Handle(state, current, request.Q("buildLabel") ?? current?.Value<string>("BuildLabel") ?? options.FallbackBuildLabel, request);
        }
        if (WorldApi.Controllers.Contains(controller))
        {
            var current = request.Q("accountId") is null ? null : accounts.Authenticate(state, request);
            return new WorldApi(clock, options).Handle(controller, state, request.Q("buildLabel")?.Replace(' ', '+') ?? current?.Value<string>("BuildLabel") ?? options.FallbackBuildLabel, request);
        }
        if (controller is "getAccountIdGetController" or "getAccountIdPostController")
        {
            var name = request.Q("targetName") ?? request.ObjectBody().RequiredString("targetName");
            name = name.TrimEnd('\ue000', '\ue001', '\ue002', '\ue003', '\ue004', '\ue005');
            var other = Accounts.All(state).FirstOrDefault(x => x.Value<string>("DisplayName") == name) ?? throw new ApiException(409, "Given Username does not exist.");
            return ApiResponse.Text(other.Value<string>("id") + "," + other.Value<string>("DisplayName"));
        }
        if (controller == "surveysController") return ApiResponse.Json(new { SurveyGroups = Array.Empty<object>() });
        if (controller == "marketRecommendationsController") return ApiResponse.Json(new { MarketRecommendations = new { Featured = Array.Empty<object>(), Popular = Array.Empty<object>() } });
        if (controller == "marketSearchRecommendationsController") return ApiResponse.Text("OK");
        if (controller is "aggregateSessionsController" or "findSessionsController") return sessions.Handle(controller, state, null, request);
        if (StatsApi.Controllers.Contains(controller) && controller is not ("uploadController" or "getProfileViewingDataPostController")) return stats.Handle(controller, state, null, request);
        var account = accounts.Authenticate(state, request);
        if (controller == "goalsController") return new EventApi(items.Value, clock, options.SyncOfficialEvents).Handle(state, account, request);
        if (controller == "inventoryController") new EventApi(items.Value, clock).Refresh(account);
        if (AssistanceApi.Controllers.Contains(controller)) return new AssistanceApi(items.Value, clock).Handle(controller, state, account, request);
        if (WeeklyApi.Controllers.Contains(controller)) return new WeeklyApi(items.Value, clock).Handle(controller, account, request);
        if (SellApi.Controllers.Contains(controller)) return new SellApi().Handle(account, request);
        if (TradingApi.Controllers.Contains(controller)) return new TradingApi(clock).Handle(state, account, request);
        if (GiftingApi.Controllers.Contains(controller)) return new GiftingApi(items.Value, clock, options.SyncOfficialEvents).Handle(state, account, request);
        if (HelminthApi.Controllers.Contains(controller)) return new HelminthApi(clock).Handle(account, request);
        if (NemesisApi.Controllers.Contains(controller)) return new NemesisApi(items.Value, clock).Handle(account, request);
        if (CustomApi.Controllers.Contains(controller)) return new CustomApi(items.Value, clock, options).Handle(controller, state, account, request);
        if (GuildExtrasApi.Controllers.Contains(controller)) return new GuildExtrasApi(clock).Handle(controller, state, account, request);
        if (ResearchApi.Controllers.Contains(controller)) return new ResearchApi(items.Value, clock).Handle(state, account, request);
        if (DojoApi.Controllers.Contains(controller)) return new DojoApi(items.Value, clock).Handle(controller, state, account, request);
        if (VaultApi.Controllers.Contains(controller))
        {
            new DojoApi(items.Value, clock).Refresh(state, GuildApi.Own(state, account));
            return new VaultApi().Handle(controller, state, account, request);
        }
        if (controller == "setPlacedDecoInfoController" && request.ObjectBody()["GuildId"] is not null)
        {
            var body = request.ObjectBody(); var guild = GuildApi.Own(state, account, Wire.Id(body["GuildId"])); var room = DojoApi.Component(guild, body.RequiredString("ComponentId")); DojoApi.Decorator(guild, account, room);
            var deco = room.Array("Decos").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["id"]) == body.Value<string>("DecoId")) ?? throw new ApiException(404, "Dojo decoration not found");
            foreach (var field in new[] { "PictureFrameInfo", "CustomizationInfo", "AnimPoseItem" }) if (body[field] is JToken value) deco[field] = value.DeepClone(); return ApiResponse.Text();
        }
        if (GuildApi.Controllers.Contains(controller)) return new GuildApi(clock).Handle(controller, state, account, request);
        if (AllianceApi.Controllers.Contains(controller)) return new AllianceApi(clock).Handle(controller, state, account, request);
        if (PersonalRoomsApi.Controllers.Contains(controller)) return new PersonalRoomsApi(clock).Handle(controller, account, request);
        if (DroneApi.Controllers.Contains(controller)) return new DroneApi(clock).Handle(account, request);
        if (RailjackApi.Controllers.Contains(controller)) return new RailjackApi().Handle(controller, account, request);
        if (ModularApi.Controllers.Contains(controller)) return new ModularApi(items.Value, clock).Handle(controller, account, request);
        if (PetApi.Controllers.Contains(controller)) return new PetApi().Handle(controller, account, request);
        if (CalendarApi.Controllers.Contains(controller)) return new CalendarApi(items.Value, clock).Handle(controller, account, request, state);
        if (EnhancementApi.Controllers.Contains(controller)) return new EnhancementApi(items.Value, clock).Handle(controller, account, request);
        if (RelicApi.Controllers.Contains(controller)) return new RelicApi(items.Value, clock).Handle(controller, account, request);
        if (SupportApi.Controllers.Contains(controller)) return new SupportApi(items.Value, clock).Handle(controller, state, account, request);
        if (ModApi.Controllers.Contains(controller)) return new ModApi().Handle(controller, account, request);
        if (FusionApi.Controllers.Contains(controller)) return new FusionApi().Handle(controller, account, request);
        if (SyndicateApi.Controllers.Contains(controller)) return new SyndicateApi(items.Value, clock).Handle(controller, account, request);
        if (Dialogues.Controllers.Contains(controller)) return new Dialogues(items.Value, clock).Handle(controller, account, request);
        if (RivenApi.Controllers.Contains(controller)) return new RivenApi().Handle(controller, account, request);
        if (FocusApi.Controllers.Contains(controller)) return new FocusApi().Handle(account, request);
        if (LoginRewardsApi.Controllers.Contains(controller)) return new LoginRewardsApi(items.Value, clock).Handle(controller, account, request);
        if (QuestApi.Controllers.Contains(controller)) return new QuestApi(items.Value, clock).Handle(controller, account, request);
        if (ChallengeApi.Controllers.Contains(controller)) return new ChallengeApi(items.Value, clock).Handle(controller, account, request, state);
        if (controller == "missionInventoryUpdateController") return new MissionApi(items.Value, clock, options.SyncOfficialEvents, store.ReplayMissionReceipt).Handle(account, request, state);
        if (StatsApi.Controllers.Contains(controller)) return stats.Handle(controller, state, account, request);
        if (ProgressApi.Controllers.Contains(controller)) return progress.Handle(controller, account, request);
        if (controller == "inboxController") return new InboxApi(items.Value, clock).Handle(account, request, state);
        if (Sessions.Controllers.Contains(controller)) return sessions.Handle(controller, state, account, request);
        if (SocialApi.Controllers.Contains(controller)) return social.Handle(controller, state, account, request);
        if (EconomyApi.Controllers.Contains(controller)) return new EconomyApi(items.Value, clock, options.SyncOfficialEvents).Handle(controller, state, account, request);
        if (controller == "saveLoadoutController") return CustomizationApi.SaveLoadout(account, request.ObjectBody());
        if (controller is "setShipCustomizationsController" or "setActiveShipController" or "setShipFavouriteLoadoutController" or "getShipController") return CustomizationApi.Ship(controller, account, request);
        if (controller == "getSkuCatalogController") return ApiResponse.Json(Assets.Json("fixed_responses/getSkuCatalogU40.json"));
        if (controller == "changePasswordController")
        {
            var body = request.ObjectBody();
            if (!Accounts.VerifyPassword(body.RequiredString("currentPassword", 4096), account.Value<string>("credential")!)) throw new ApiException(403, "Wrong password");
            account["credential"] = Accounts.HashPassword(body.RequiredString("newPassword", 4096));
            account["Nonce"] = 0;
            return ApiResponse.Text();
        }
        if (controller == "renameAccountController") { Rename(state, account, request.Q("newname") ?? ""); return ApiResponse.Text(); }
        return player.Handle(controller, state, account, request);
    }

    private async Task<ApiResponse> Control(ApiRequest request)
    {
        accounts.Admin(request);
        if (!request.Path.StartsWith("/control/v1/", StringComparison.Ordinal)) throw new ApiException(404, "Unknown management API version");
        var path = request.Path["/control/v1/".Length..].Trim('/');
        if (request.Method == "GET")
        {
            if (path == "snapshot") return await store.Read(state => ApiResponse.Json(new
            {
                name = ServerIdentity.Name(state, options), apiVersion = ServerIdentity.ApiVersion, status = maintenance ? "maintenance" : "running", started, uptimeSeconds = (clock.GetUtcNow() - started).TotalSeconds,
                totalRequests = Interlocked.Read(ref totalRequests), failedRequests = Interlocked.Read(ref failedRequests),
                players = Accounts.All(state).Count(), online = Accounts.All(state).Count(x => x.Value<long>("Nonce") != 0 && x.Value<bool?>("Dropped") != true),
                sessions = state.Obj("sessions").Count, guilds = state.Obj("guilds").Count, revision = state.Value<long>("revision"),
                routes = new { total = Routes.All.Count(), ported = Routes.All.Count(x => x.Status == "ported"), partial = Routes.All.Count(x => x.Status == "partial"), pending = Routes.All.Count(x => x.Status == "pending") },
                runtime = ".NET " + Environment.Version, upstream = Assets.Json("upstream.json")
            }));
            if (path == "routes") return ApiResponse.Json(Routes.All);
            if (path == "logs") return ApiResponse.Json(logs.Where(x => x.Id > (long.TryParse(request.Q("after"), out var after) ? after : 0)).ToArray());
            if (path == "catalog") return ApiResponse.Json(items.Value.WithLanguage(request.Q("lang")).Search(request.Q("q") ?? "", request.Q("category"), int.TryParse(request.Q("skip"), out var skip) ? skip : 0));
            if (path == "riven/catalog") return ApiResponse.Json(RivenCalculator.Catalog(items.Value.WithLanguage(request.Q("lang")), request.Q("type")));
            if (path == "editor/permissions") return await store.Read(s => ApiResponse.Json(EditorPermissions.Read(s)));
            if (path == "editor/server") return await store.Read(s => ApiResponse.Json(ServerSettingsEditor.Read(s, options)));
            if (path == "editor/server/revision") return await store.Read(s => ApiResponse.Json(new { version = ServerSettingsEditor.Version(s) }));
            if (path == "config") return await store.Read(s => ApiResponse.Json(new JObject { ["serverName"] = ServerIdentity.Name(s, options), ["autoCreateAccount"] = s.Obj("config").Value<bool?>("autoCreateAccount") ?? options.AutoCreateAccount, ["allowPlayerRegistration"] = s.Obj("config").Value<bool?>("allowPlayerRegistration") ?? options.AllowPlayerRegistration, ["allowPlayerCurrencyGrant"] = s.Obj("config").Value<bool?>("allowPlayerCurrencyGrant") ?? options.AllowPlayerCurrencyGrant, ["allowPlayerItemGrant"] = PlayerPermissions.Items(s, options), ["publicUrl"] = options.PublicUrl, ["listenUrls"] = new JArray(options.ListenUrls), ["fallbackBuildLabel"] = options.FallbackBuildLabel }));
            if (path == "accounts") return await store.Read(s => ApiResponse.Json(new JArray(Accounts.All(s).Select(Accounts.Public))));
            if (path == "news") return await store.Read(s => ApiResponse.Json(Announcements.News(s)));
            if (path == "messages") return await store.Read(s => ApiResponse.Json(Announcements.History(s)));
            if (path == "world") return await store.Read(s => ApiResponse.Json(s.Obj("worldState")));
            if (path == "events") return ApiResponse.Json(await OfficialEventSync.Status());
            var segments = path.Split('/');
            if (segments.Length == 3 && segments[0] == "accounts") return await store.Read(s =>
            {
                var account = Find(s, segments[1]);
                return segments[2] switch
                {
                    "editor" => ApiResponse.Json(new AccountEditor(items.Value, clock, options).Read(s, account, request)),
                    "editor-revision" => ApiResponse.Json(new { version = AccountEditor.Version(s, account) }),
                    "inventory" or "export" => ApiResponse.Json(Inventory.Export(account)),
                    "archive" => ApiResponse.Json(InventoryArchive.Read(s, account)),
                    "profile" => ApiResponse.Json(Accounts.Public(account)),
                    _ => throw new ApiException(404, "Unknown account operation")
                };
            });
            throw new ApiException(404, "Unknown management endpoint");
        }
        if (request.Method != "POST") throw new ApiException(405, "Use GET or POST");
        var body = request.ObjectBody();
        if (path == "events/sync") return ApiResponse.Json(await OfficialEventSync.Synchronize());
        if (path == "riven/calculate") return ApiResponse.Json(RivenCalculator.Calculate(body, items.Value.WithLanguage(request.Q("lang"))));
        if (path == "shutdown") { ShutdownRequested?.Invoke(); return ApiResponse.Json(new { stopping = true }); }
        if (path == "maintenance") { maintenance = body.Value<bool?>("enabled") ?? throw new ApiException(400, "Missing enabled"); return ApiResponse.Json(new { maintenance }); }
        return await store.Update(state =>
        {
            if (path == "editor/permissions") return ApiResponse.Json(EditorPermissions.Save(state, body));
            if (path == "editor/server") return ApiResponse.Json(ServerSettingsEditor.Save(state, body, options));
            if (path == "accounts") return ApiResponse.Json(Accounts.Public(accounts.Create(state, body.RequiredString("email", 254), Accounts.GamePassword(body.RequiredString("password", 256)), body.Value<string>("displayName"))), 201);
            if (path == "config")
            {
                var keys = new[] { "autoCreateAccount", "allowPlayerRegistration", "allowPlayerCurrencyGrant", "allowPlayerItemGrant" };
                if (!keys.Any(k => body[k] is not null) && body["serverName"] is null) throw new ApiException(400, "Missing settings");
                if (body["serverName"] is not null) state.Obj("config")["serverName"] = ServerIdentity.ValidateName(body.RequiredString("serverName", 64));
                foreach (var key in keys.Where(k => body[k] is not null))
                {
                    if (body[key]!.Type != JTokenType.Boolean) throw new ApiException(400, "Invalid " + key);
                    state.Obj("config")[key] = body[key]!.DeepClone();
                }
                return ApiResponse.Json(state["config"]);
            }
            if (path == "world") { state["worldState"] = body.DeepClone(); return ApiResponse.Json(new { saved = true, gameApiEnabled = true }); }
            if (path == "news/save") return ApiResponse.Json(new Announcements(items.Value, clock).SaveNews(state, body));
            if (path == "news/delete") { Announcements.DeleteNews(state, body); return ApiResponse.Json(new { deleted = true }); }
            if (path == "messages/publish") return ApiResponse.Json(new Announcements(items.Value, clock).PublishMail(state, body), 201);
            var segments = path.Split('/');
            if (segments.Length != 3 || segments[0] != "accounts") throw new ApiException(404, "Unknown management endpoint");
            var account = Find(state, segments[1]); var inv = account.Obj("Inventory");
            switch (segments[2])
            {
                case "editor": return ApiResponse.Json(new AccountEditor(items.Value, clock, options).Apply(state, account, body));
                case "currency": return ApiResponse.Json(Inventory.ChangeCurrency(inv, body.RequiredString("currency"), body.Integer("delta", -999_999_999), applyRules: false));
                case "item":
                    return ApiResponse.Json(new ItemAcquisition(items.Value, clock, account).Add(inv, body.RequiredString("type"), (int)body.Integer("count", 1, 100), premium: true));
                case "message": return ApiResponse.Json(InboxApi.Create(account, body, clock.GetUtcNow()), 201);
                case "remove-item":
                    var selectedCategory = body.RequiredString("category");
                    if (Inventory.EquipmentKeys.Contains(selectedCategory)) Inventory.Equipment(inv, selectedCategory, body.RequiredString("id")).Remove();
                    else if (Inventory.CountedKeys.Contains(selectedCategory)) Inventory.AddCount(inv, selectedCategory, body.RequiredString("type"), -body.Integer("count", 1));
                    else throw new ApiException(400, "Unknown category");
                    return ApiResponse.Json(new { removed = true });
                case "rename": Rename(state, account, body.RequiredString("name", 24)); return ApiResponse.Json(Accounts.Public(account));
                case "ban": account["Banned"] = body.Value<bool?>("banned") ?? throw new ApiException(400, "Missing banned"); account["Nonce"] = 0; return ApiResponse.Json(Accounts.Public(account));
                case "kick": account["Nonce"] = 0; return ApiResponse.Json(new { kicked = true });
                case "tutorial":
                    if (body["skipTutorial"]?.Type != JTokenType.Boolean) throw new ApiException(400, "Missing skipTutorial boolean");
                    account["SkipTutorial"] = body.Value<bool>("skipTutorial");
                    if (account.Value<bool>("SkipTutorial")) TutorialProgress.Apply(account, items.Value, clock);
                    return ApiResponse.Json(Accounts.Public(account));
                case "password": account["credential"] = Accounts.HashPassword(Accounts.GamePassword(body.RequiredString("password", 256))); account["Nonce"] = 0; return ApiResponse.Json(new { changed = true });
                case "import":
                    return ApiResponse.Json(InventoryArchive.Import(store, state, account, body, items.Value, clock, requireVersion: false));
                default: throw new ApiException(404, "Unknown account operation");
            }
        });
    }
    private static JObject Find(JObject state, string id) => state.Obj("accounts")[id] as JObject ?? throw new ApiException(404, "Account not found");
    private static void Rename(JObject state, JObject account, string name)
    {
        if (name.Length is < 1 or > 24 || name == "all" || name.Any(char.IsControl)) throw new ApiException(400, "Invalid display name");
        if (Accounts.All(state).Any(x => x.Value<string>("id") != account.Value<string>("id") && x.Value<string>("DisplayName") == name)) throw new ApiException(409, "DisplayName already in use");
        account["DisplayName"] = name;
    }
}