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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed class SocialApi(TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["getFriendsController", "addPendingFriendGetController", "addPendingFriendPostController", "addFriendGetController", "addFriendPostController", "pendingFriendsViewedController", "setFriendNoteController", "addFriendTitleController", "getIgnoredUsersController", "addIgnoredUserController", "removeIgnoredUserController", "addFriendImageGetController", "addFriendImagePostController", "removeFriendGetController", "removeFriendPostController"];
    public ApiResponse Handle(string controller, JObject state, JObject account, ApiRequest request)
    {
        var id = account.Value<string>("id")!;
        var body = request.ObjectBody();
        var edges = state.Array("friendships");
        JObject? Edge(string a, string b) => edges.OfType<JObject>().FirstOrDefault(x => x.Value<string>("owner") == a && x.Value<string>("friend") == b);
        if (controller is "addFriendImageGetController" or "addFriendImagePostController") { account.Obj("Inventory")["ActiveAvatarImageType"] = request.Q("avatarImageType") ?? body.RequiredString("AvatarImageType"); return ApiResponse.Json(new JObject()); }
        if (controller is "removeFriendGetController" or "removeFriendPostController")
        {
            IEnumerable<string> removed;
            if (request.Method == "GET") removed = request.Q("all") is not null
                ? edges.OfType<JObject>().Where(x => x.Value<string>("friend") == id && Edge(id, x.RequiredString("owner")) is null).Select(x => x.RequiredString("owner")).ToArray()
                : [request.Q("friendId") ?? throw new ApiException(400, "Missing friendId")];
            else
            {
                var days = body.Integer("DaysLoggedOut", 0, 100000); var skip = (body["SkipFriendIds"] as JArray ?? []).Select(x => x.ToString()).ToArray(); var guild = Wire.Id(account.Obj("Inventory")["GuildId"]);
                removed = edges.OfType<JObject>().Where(x => x.Value<string>("owner") == id).Select(x => x.RequiredString("friend")).Where(friend =>
                {
                    if (skip.Any(x => x == friend || x.Length >= 14 && friend.Length >= 14 && x.Substring(6, 8) == friend.Substring(6, 8))) return false;
                    if (state.Obj("accounts")[friend] is not JObject other) return true;
                    if (body.Value<bool>("SkipClanmates") && guild.Length > 0 && Wire.Id(other.Obj("Inventory")["GuildId"]) == guild) return false;
                    return (clock.GetUtcNow().ToUnixTimeMilliseconds() - Wire.DateMs(other["LastLogin"])) / (double)WorldData.Day >= days;
                }).ToArray();
            }
            var ids = removed.Distinct().ToArray();
            foreach (var edge in edges.OfType<JObject>().Where(x => x.Value<string>("owner") == id && ids.Contains(x.Value<string>("friend")) || x.Value<string>("friend") == id && ids.Contains(x.Value<string>("owner"))).ToArray()) edge.Remove();
            var build = GameVersion.For(account);
            return ApiResponse.Json(build < GameVersion.Of("40.0.0") ? new JObject { ["Friends"] = new JArray(ids.Select(x => GameVersion.Oid(x, build))) } : new JObject { ["FriendNames"] = new JArray(ids.Select(x => state.Obj("accounts")[x]).OfType<JObject>().Select(x => x.Value<string>("DisplayName") + "\ue000")) });
        }
        if (controller == "addFriendTitleController") { account.Obj("Inventory")["TitleType"] = body.RequiredString("TitleType"); return ApiResponse.Json(new JObject()); }
        if (controller == "getFriendsController")
        {
            var current = new JArray(); var incoming = new JArray(); var outgoing = new JArray();
            foreach (var other in Accounts.All(state).Where(x => x.Value<string>("id") != id))
            {
                var otherId = other.Value<string>("id")!;
                var a = Edge(id, otherId); var b = Edge(otherId, id);
                if (a is not null && b is not null) current.Add(Info(other, a));
                else if (a is not null) outgoing.Add(Info(other, a));
                else if (b is not null) incoming.Add(Info(other, b));
            }
            var response = new JObject { ["Current"] = current, ["IncomingFriendRequests"] = incoming, ["OutgoingFriendRequests"] = outgoing };
            if (GameVersion.For(account) < GameVersion.August2026 && account.Obj("Inventory")["ActiveAvatarImageType"]?.Type == JTokenType.String)
                response["ActiveAvatarImageType"] = account.Obj("Inventory")["ActiveAvatarImageType"]!.DeepClone();
            return ApiResponse.Json(response);
        }
        if (controller.StartsWith("addPendingFriend", StringComparison.Ordinal))
        {
            var name = request.Q("friend") ?? body.RequiredString("friend");
            var other = Accounts.All(state).FirstOrDefault(x => x.Value<string>("DisplayName") == name) ?? throw new ApiException(400, "Given Username does not exist.");
            var otherId = other.Value<string>("id")!;
            if (id == otherId || Edge(id, otherId) is not null) throw new ApiException(409, "Already in friend list");
            var restriction = other.Obj("Inventory").Obj("Settings").Value<string>("FriendInvRestriction");
            if (restriction == "GIFT_MODE_NONE" || (restriction == "GIFT_MODE_FRIENDS" && !Accounts.All(state).Any(x =>
                Edge(id, x.Value<string>("id")!) is not null && Edge(x.Value<string>("id")!, id) is not null &&
                Edge(otherId, x.Value<string>("id")!) is not null && Edge(x.Value<string>("id")!, otherId) is not null)))
                throw new ApiException(403, "Friend Invite Restriction");
            var edge = new JObject { ["owner"] = id, ["friend"] = otherId, ["Note"] = body["message"], ["NewRequest"] = true };
            edges.Add(edge);
            return ApiResponse.Json(new JObject { ["Friend"] = Info(other, edge) });
        }
        if (controller is "addFriendGetController" or "addFriendPostController")
        {
            var selected = request.Q("friend") ?? body.RequiredString("friend");
            var friends = new JArray();
            foreach (var edge in edges.OfType<JObject>().Where(x => x.Value<string>("friend") == id && (selected == "all" || x.Value<string>("owner") == selected)).ToArray())
            {
                var otherId = edge.Value<string>("owner")!;
                if (Edge(id, otherId) is not null) continue;
                edge.Remove("NewRequest");
                edges.Add(new JObject { ["owner"] = id, ["friend"] = otherId, ["Note"] = edge["Note"] });
                if (state.Obj("accounts")[otherId] is JObject other) friends.Add(Info(other, edge));
            }
            return request.Method == "GET" ? ApiResponse.Text() : ApiResponse.Json(new JObject { ["Friends"] = friends });
        }
        if (controller == "pendingFriendsViewedController")
        {
            foreach (var friend in body["friends"] as JArray ?? throw new ApiException(400, "Missing friends")) Edge(friend.ToString(), id)?.Remove("NewRequest");
            return ApiResponse.Text();
        }
        if (controller == "setFriendNoteController")
        {
            var friend = body.RequiredString("FriendId"); var edge = Edge(id, friend);
            if (edge is not null) { var key = body.ContainsKey("Note") ? "Note" : "Favorite"; edge[key] = body[key]; }
            return ApiResponse.Json(new JObject { ["Id"] = friend, ["SetNote"] = body.ContainsKey("Note"), ["Note"] = edge?["Note"], ["Favorite"] = edge?["Favorite"] });
        }
        if (controller == "getIgnoredUsersController")
            return ApiResponse.Json(new JObject { ["IgnoredUsers"] = new JArray(account.Array("Ignored").Select(x => state.Obj("accounts")[x.ToString()]).OfType<JObject>().Select(x => new JObject { ["_id"] = Wire.Oid(x.Value<string>("id")!), ["DisplayName"] = x.Value<string>("DisplayName") + "\ue000" })) });
        var player = body.RequiredString("playerName").TrimEnd('\ue000', '\ue001', '\ue002', '\ue003', '\ue004', '\ue005');
        var target = Accounts.All(state).FirstOrDefault(x => x.Value<string>("DisplayName") == player);
        if (controller == "addIgnoredUserController")
        {
            if (target is null) throw new ApiException(400, "Unknown player");
            account.Array("Ignored").UniqueAdd(target["id"]!);
            return ApiResponse.Json(new JObject { ["Ignored"] = new JObject { ["_id"] = Wire.Oid(target.Value<string>("id")!), ["DisplayName"] = body["playerName"] } });
        }
        foreach (var item in account.Array("Ignored").Where(x => x.ToString() == target?.Value<string>("id")).ToArray()) item.Remove();
        return ApiResponse.Text();
    }
    public static JObject Info(JObject account, JObject relation) => new()
    {
        ["_id"] = Wire.Oid(account.Value<string>("id")!), ["DisplayName"] = account["DisplayName"],
        ["LastLogin"] = Wire.Date(DateTimeOffset.TryParse(account.Value<string>("LastLogin"), out var date) ? date.ToUnixTimeMilliseconds() : 0),
        ["LastPlatform"] = 0, ["PlayerLevel"] = AccountRules.Mastery(account.Obj("Inventory")),
        ["ActiveAvatarImageType"] = account.Obj("Inventory")["ActiveAvatarImageType"], ["Note"] = relation["Note"], ["Favorite"] = relation["Favorite"], ["NewRequest"] = relation["NewRequest"]
    };
}