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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using Newtonsoft.Json.Linq;

namespace XFEWarframe.Core.Services;

public sealed class Sessions(TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["hostSessionController", "joinSessionGetController", "joinSessionPostController", "deleteSessionController", "updateSessionGetController", "updateSessionPostController", "findSessionsController", "aggregateSessionsController"];
    private static readonly string[] Fields = ["maxPlayers", "minPlayers", "privateSlots", "scoreLimit", "timeLimit", "gameModeId", "eloRating", "regionId", "difficulty", "hasStarted", "enableVoice", "matchType", "maps", "originalSessionId", "customSettings", "rewardSeed", "guildId", "buildId", "platform", "xplatform", "freePublic", "freePrivate", "fullReset"];
    public ApiResponse Handle(string controller, JObject state, JObject? account, ApiRequest request)
    {
        var sessions = state.Obj("sessions");
        var now = clock.GetUtcNow().ToUnixTimeMilliseconds();
        foreach (var expired in sessions.Properties().Where(x => now - x.Value.Value<long>("lastUpdate") > 300000).ToArray()) expired.Remove();
        if (controller == "aggregateSessionsController")
            return ApiResponse.Json(new JObject { ["Results"] = new JArray(sessions.Properties().Select(x => (JObject)x.Value).Where(x => x.Value<int>("freePublic") != 0).GroupBy(x => x.Value<int>("gameModeId")).Select(g => new JObject { ["gameModeId"] = g.Key, ["count"] = g.Count() })) });
        JObject body;
        if (request.Body.Length != 0 && !request.Body.TrimStart().StartsWith('{') && controller == "updateSessionPostController")
        {
            body = new JObject();
            foreach (var pair in request.Body.Split('&'))
            {
                var parts = pair.Split('=', 2);
                if (parts.Length == 2 && Fields.Contains(parts[0]) && long.TryParse(parts[1], out var value)) body[parts[0]] = value;
            }
        }
        else body = request.ObjectBody();
        if (controller == "findSessionsController")
        {
            var found = sessions.Properties().Select(x => (JObject)x.Value).Where(x => Matches(x, body))
                .Select(x => new JObject { ["id"] = x["id"], ["createdBy"] = x["creatorId"] }).ToArray();
            return ApiResponse.Json(found.Length == 0 ? new JObject() : new JObject { ["queryId"] = body["queryId"], ["Sessions"] = new JArray(found) });
        }
        if (account is null) throw new ApiException(401, "Authentication required");
        if (controller == "hostSessionController")
        {
            var session = new JObject();
            foreach (var field in Fields) if (body.ContainsKey(field)) session[field] = body[field];
            var id = Wire.NewId();
            session["id"] = id; session["creatorId"] = account["id"]; session["lastUpdate"] = now;
            session["hasStarted"] ??= false; session["fullReset"] = 0;
            if (session.Value<long?>("rewardSeed") is null or 0 or -1) session["rewardSeed"] = Wire.Seed();
            sessions[id] = session;
            return ApiResponse.Json(new JObject { ["sessionId"] = Wire.Oid(id), ["rewardSeed"] = session["rewardSeed"] });
        }
        var sessionId = request.Q("sessionId") ?? body["sessionIds"]?[0]?.ToString() ?? throw new ApiException(400, "Missing sessionId");
        var existing = sessions[sessionId] as JObject;
        if (controller is "joinSessionGetController" or "joinSessionPostController")
            return ApiResponse.Json(new JObject { ["sessionId"] = Wire.Oid(sessionId), ["rewardSeed"] = existing?["rewardSeed"] ?? new JValue(Wire.Seed()) });
        if (existing is null) throw new ApiException(400, "Session not found");
        if (existing.Value<string>("creatorId") != account.Value<string>("id")) throw new ApiException(403, "Only the session host may change it");
        if (controller == "deleteSessionController") { sessions.Remove(sessionId); return ApiResponse.Text("OK"); }
        foreach (var field in Fields) if (body.ContainsKey(field)) existing[field] = body[field];
        existing["lastUpdate"] = now;
        return ApiResponse.Json(new JObject());
    }
    private static bool Matches(JObject session, JObject query)
    {
        if (query.ContainsKey("id")) return JToken.DeepEquals(session["id"], query["id"]);
        if (query.ContainsKey("originalSessionId")) return JToken.DeepEquals(session["originalSessionId"], query["originalSessionId"]);
        if (session.Value<bool?>("hasStarted") == true) return false;
        foreach (var key in new[] { "buildId", "gameModeId", "regionId" }) if (query.ContainsKey(key) && !JToken.DeepEquals(session[key], query[key])) return false;
        if (query.Value<int?>("freePublic") > 0 && session.Value<int>("freePublic") < 1) return false;
        if (query.ContainsKey("eloRating") && query.ContainsKey("maxEloDifference") && Math.Abs(session.Value<double>("eloRating") - query.Value<double>("eloRating")) > query.Value<double>("maxEloDifference")) return false;
        if (query.ContainsKey("maps") && !JToken.DeepEquals(session["maps"], query["maps"]) && !(session["maps"] as JArray ?? []).Any(x => JToken.DeepEquals(x, query["maps"]))) return false;
        return true;
    }
}