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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public sealed class PersonalRoomsApi(TimeProvider clock)
{
    public static readonly HashSet<string> Controllers = ["getShipController", "shipDecorationsController", "setPlacedDecoInfoController", "gardeningController", "apartmentController", "setShipVignetteController", "researchMushroomController"];
    public static JObject Ensure(JObject account)
    {
        var rooms = account.Obj("PersonalRooms");
        foreach (var (location, defaults) in new (string, (string, int)[])[] {
            ("Ship", [("AlchemyRoom", 1600), ("BridgeRoom", 1600), ("LisetRoom", 1000), ("OperatorChamberRoom", 1600), ("OutsideRoom", 1600), ("PersonalQuartersRoom", 1600)]),
            ("Apartment", [("ElevatorLanding", 1600), ("ApartmentRoomA", 1000), ("ApartmentRoomB", 1600), ("ApartmentRoomC", 1600), ("DuviriHallway", 1600)]),
            ("TailorShop", [("LabRoom", 4000), ("LivingQuartersRoom", 3000), ("HelminthRoom", 2000)]) })
        {
            var target = rooms.Obj(location); var list = target.Array("Rooms");
            foreach (var (name, capacity) in defaults) if (!list.Any(x => x.Value<string>("Name") == name)) list.Add(new JObject { ["Name"] = name, ["MaxCapacity"] = capacity, ["PlacedDecos"] = new JArray() });
            if (location != "Ship") target.Array("FavouriteLoadouts");
        }
        var ship = rooms.Obj("Ship"); if (ship.Value<string>("BootLocation") is null or "Liset") ship["BootLocation"] = "LISET";
        if (rooms["activeShipId"] is null) rooms["activeShipId"] = Wire.Id(account.Obj("Inventory").Array("Ships").FirstOrDefault()?["ItemId"]);
        ship.Array("Features").UniqueAdd("/Lotus/Types/Items/ShipFeatureItems/EarthNavigationFeatureItem");
        ShipFeatureProgress.RestoreCompletedQuests(account);
        return rooms;
    }
    public ApiResponse Handle(string controller, JObject account, ApiRequest request)
    {
        var body = request.ObjectBody(); var rooms = Ensure(account); var inv = account.Obj("Inventory");
        if (controller == "getShipController")
        {
            if (rooms.Obj("Apartment").Obj("Gardening").Array("Planters").Count == 0) rooms.Obj("Apartment")["Gardening"] = Garden();
            var ship = rooms.Obj("Ship"); ship["ContentUrlSignature"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
            var copy = (JObject)ship.DeepClone(); copy["ShipId"] = Wire.Oid(rooms.Value<string>("activeShipId")!);
            var response = new JObject { ["ShipOwnerId"] = account["id"]!.DeepClone(), ["Ship"] = copy, ["Apartment"] = rooms["Apartment"]!.DeepClone(), ["TailorShop"] = rooms["TailorShop"]!.DeepClone() };
            if (GameVersion.For(account) < GameVersion.August2026) response["LoadOutInventory"] = new JObject { ["LoadOutPresets"] = account.Obj("Loadouts").DeepClone() };
            return ApiResponse.Json(response);
        }
        if (controller == "apartmentController")
        {
            var result = new JObject(); foreach (var (query, field, response) in new[] { ("backdrop", "VideoWallBackdrop", "NewBackdropItem"), ("soundscape", "Soundscape", "NewSoundscapeItem") })
                if (request.Q(query) is string value) { rooms.Obj("Apartment")[field] = value; result[response] = value; }
            return ApiResponse.Json(result);
        }
        if (controller == "gardeningController") return Harvest(inv, rooms, body);
        if (controller == "setShipVignetteController") return Vignette(inv, rooms.Obj("Ship"), body);
        if (controller == "researchMushroomController") return Mushroom(inv, body);
        if (controller == "setPlacedDecoInfoController" && body["GuildId"] is not null) throw new ApiException(501, "Dojo decoration customization requires the guild handler");
        var list = rooms.Obj(body.Value<string>("BootLocation") == "SHOP" ? "TailorShop" : body.Value<string>("BootLocation") == "APARTMENT" || body.Value<bool>("IsApartment") ? "Apartment" : "Ship").Array("Rooms");
        var room = list.OfType<JObject>().FirstOrDefault(x => x.Value<string>("Name") == body.Value<string>("Room")) ?? throw new ApiException(404, "Unknown room");
        if (controller == "setPlacedDecoInfoController")
        {
            var deco = Decoration(room, body.RequiredString("DecoId")); foreach (var field in new[] { "PictureFrameInfo", "CustomizationInfo", "AnimPoseItem" }) if (body[field] is JToken value) deco[field] = value.DeepClone();
            return ApiResponse.Text();
        }
        if (request.Q("reset") == "1")
        {
            foreach (var deco in room.Array("PlacedDecos").OfType<JObject>().ToArray()) { Return(inv, deco); room["MaxCapacity"] = checked(room.Value<int>("MaxCapacity") + Meta(deco.RequiredString("Type")).Meta.Value<int>("capacityCost")); deco.Remove(); }
            return ApiResponse.Json(new JObject { ["ResetRoom"] = room["Name"]!.DeepClone(), ["ClaimedDecos"] = new JArray(), ["NewCapacity"] = room["MaxCapacity"]!.DeepClone() });
        }
        if (body.Value<string>("RemoveId") is string remove)
        {
            var deco = Decoration(room, remove); Return(inv, deco); room["MaxCapacity"] = checked(room.Value<int>("MaxCapacity") + Meta(deco.RequiredString("Type")).Meta.Value<int>("capacityCost")); deco.Remove();
            return ApiResponse.Json(new { DecoId = remove, Room = body.Value<string>("Room"), IsApartment = body.Value<bool>("IsApartment"), MaxCapacityIncrease = 0 });
        }
        var type = body.RequiredString("Type"); var (itemType, meta) = Meta(type); var cost = meta.Value<int>("capacityCost"); var target = new JObject(); var moved = body.Value<string>("MoveId"); var oldName = body.Value<string>("OldRoom"); var sameRoom = moved is not null && oldName == room.Value<string>("Name");
        if (!sameRoom && room.Value<int>("MaxCapacity") < cost) throw new ApiException(409, "Decoration exceeds room capacity");
        if (moved is not null)
        {
            var old = list.OfType<JObject>().FirstOrDefault(x => x.Value<string>("Name") == oldName) ?? throw new ApiException(404, "Old room not found"); var existing = Decoration(old, moved);
            if (existing.Value<string>("Type") != type) throw new ApiException(400, "Moving a decoration cannot change its type");
            target = (JObject)existing.DeepClone(); existing.Remove(); if (!sameRoom) old["MaxCapacity"] = checked(old.Value<int>("MaxCapacity") + cost);
        }
        else
        {
            target["id"] = Wire.Oid(Wire.NewId()); target["Type"] = type;
            if (body["Sockets"] is not null) { var sockets = (int)body.Integer("Sockets", 0, 65535); Sculpture(inv, itemType, sockets, -1); target["Sockets"] = sockets; }
            else Inventory.AddCount(inv, "ShipDecorations", itemType, -1);
        }
        foreach (var name in new[] { "Pos", "Rot" })
        {
            if (body[name] is not JArray vector || vector.Count != 3 || vector.Any(x => x.Type is not (JTokenType.Integer or JTokenType.Float) || !double.IsFinite(x.Value<double>()))) throw new ApiException(400, "Invalid decoration transform"); target[name] = vector.DeepClone();
        }
        if (body["Scale"] is JToken scale) { var value = scale.Value<double>(); if (!double.IsFinite(value) || value <= 0 || value > 100) throw new ApiException(400, "Invalid decoration scale"); target["Scale"] = value; }
        room.Array("PlacedDecos").Add(target); if (!sameRoom) room["MaxCapacity"] = checked(room.Value<int>("MaxCapacity") - cost);
        return moved is null ? ApiResponse.Json(new { DecoId = Wire.Id(target["id"]), Room = body.Value<string>("Room"), IsApartment = body.Value<bool>("IsApartment"), MaxCapacityIncrease = -cost }) : ApiResponse.Json(new { OldRoom = oldName, NewRoom = body.Value<string>("Room"), IsApartment = body.Value<bool>("IsApartment"), MaxCapacityIncrease = sameRoom ? 0 : -cost });
    }
    private static JObject Decoration(JObject room, string id) => room.Array("PlacedDecos").OfType<JObject>().FirstOrDefault(x => Wire.Id(x["id"] ?? x["_id"]) == id) ?? throw new ApiException(404, "Decoration not found");
    private static (string Type, JObject Meta) Meta(string type)
    {
        var entry = GameData.Table("Resources").Properties().FirstOrDefault(x => x.Value.Value<string>("deco") == type && x.Value["capacityCost"] is not null) ?? throw new ApiException(400, "Unknown decoration type"); return (entry.Name, (JObject)entry.Value);
    }
    private static void Return(JObject inv, JObject deco)
    {
        var type = Meta(deco.RequiredString("Type")).Type; if (deco["Sockets"] is not null) Sculpture(inv, type, deco.Value<int>("Sockets"), 1); else Inventory.AddCount(inv, "ShipDecorations", type, 1);
    }
    private static void Sculpture(JObject inv, string type, int sockets, int change)
    {
        var array = inv.Array("FusionTreasures"); var item = array.OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type && x.Value<int>("Sockets") == sockets); var count = (item?.Value<int>("ItemCount") ?? 0) + change;
        if (count < 0) throw new ApiException(400, "Sculpture with these sockets is not owned");
        if (item is null) array.Add(new JObject { ["ItemType"] = type, ["Sockets"] = sockets, ["ItemCount"] = count }); else if (count == 0) item.Remove(); else item["ItemCount"] = count;
    }
    private JObject Garden() => new() { ["Planters"] = new JArray(Enumerable.Range(0, 3).Select(i => new JObject { ["Name"] = "Garden" + i, ["Plants"] = new JArray(Enumerable.Range(0, 2).Select(j => new JObject { ["PlantType"] = "/Lotus/Types/Items/Plants/MiscItems/DuvxDuviriGrowingPlant" + (char)('A' + Random.Shared.Next(6)), ["EndTime"] = Wire.Date(clock.GetUtcNow().AddHours(22).ToUnixTimeSeconds() * 1000), ["PlotIndex"] = j })) })) };
    private ApiResponse Harvest(JObject inv, JObject rooms, JObject body)
    {
        if (body.Value<string>("Mode") != "HarvestAll") throw new ApiException(400, "Unknown gardening operation"); var garden = rooms.Obj("Apartment").Obj("Gardening"); var changes = new JObject(); var rewards = new JObject(); var now = clock.GetUtcNow().ToUnixTimeMilliseconds();
        if (garden.Array("Planters").SelectMany(x => x["Plants"] ?? new JArray()).Any(x => Wire.DateMs(x["EndTime"]) > now)) throw new ApiException(409, "Plants have not finished growing");
        foreach (var planter in garden.Array("Planters").OfType<JObject>())
        {
            var items = new JArray(); rewards[planter.RequiredString("Name")] = items;
            foreach (var plant in planter.Array("Plants"))
            {
                var type = "/Lotus/Types/Gameplay/Duviri/Resource/DuviriPlantItem" + plant.Value<string>("PlantType")![^1]; var count = Random.Shared.NextDouble() < .775 ? 2 : 4;
                if (GameData.Find("Resources", type) is null) throw new ApiException(400, "Unknown plant"); InventoryProgress.Misc(inv, type, count); Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = count }) });
                items.Add(new JArray(new JObject { ["StoreItem"] = GameData.StoreType(type), ["TypeName"] = type, ["ItemCount"] = count, ["DailyCooldown"] = false, ["Rarity"] = count == 2 ? .7743589743589744 : .22564102564102564, ["ProductCategory"] = "MiscItems" }));
            }
        }
        garden = Garden(); rooms.Obj("Apartment")["Gardening"] = garden; var last = garden["Planters"]!.Last!; var leaf = last["Plants"]!.Last!;
        return ApiResponse.Json(new JObject { ["GardenTagName"] = last["Name"]!.DeepClone(), ["PlantType"] = leaf["PlantType"]!.DeepClone(), ["PlotIndex"] = leaf["PlotIndex"]!.DeepClone(), ["EndTime"] = leaf["EndTime"]!.DeepClone(), ["InventoryChanges"] = changes, ["Gardening"] = garden.DeepClone(), ["Rewards"] = rewards });
    }
    private static ApiResponse Vignette(JObject inv, JObject ship, JObject body)
    {
        var fish = body["Fish"] as JArray ?? throw new ApiException(400, "Missing vignette fish"); if (fish.Count > 100) throw new ApiException(400, "Too many vignette fish"); var old = ship.Array("VignetteFish"); var changes = new JObject();
        foreach (var type in old.Concat(fish).Select(x => x.ToString()).Where(x => x.Length > 0).Distinct())
        {
            var count = old.Count(x => x.ToString() == type) - fish.Count(x => x.ToString() == type); if (count == 0) continue;
            if (GameData.Find("Resources", type)?["dissectionParts"] is null) throw new ApiException(400, "Only fish can be placed in the vignette"); Inventory.AddCount(inv, "MiscItems", type, count); Inventory.Combine(changes, new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = count }) });
        }
        foreach (var name in new[] { "Wallpaper", "Vignette" }) ship[name] = body[name]?.DeepClone() ?? ""; ship["VignetteFish"] = fish.DeepClone();
        if (body["VignetteDecos"] is JArray decos && decos.Count > 0) throw new ApiException(400, "Place room decorations through shipDecorations");
        return ApiResponse.Json(new JObject { ["Wallpaper"] = ship["Wallpaper"]!.DeepClone(), ["Vignette"] = ship["Vignette"]!.DeepClone(), ["VignetteFish"] = fish.DeepClone(), ["InventoryChanges"] = changes });
    }
    private static ApiResponse Mushroom(JObject inv, JObject body)
    {
        if (body.Value<string>("Mode") != "r") throw new ApiException(400, "Unknown mushroom research operation"); var type = body.RequiredString("MushroomItem"); var count = (int)body.Integer("Amount", 1, 100000); var names = new[] { "Heat", "Corrosive", "Slash", "Plain", "Magnetic", "Radiation", "Impact", "Toxin", "Void", "Gas", "Blast", "Puncture", "Electric", "Viral", "Tau", "Cold" }; var totals = new[] { 18, 24, 18, 4, 24, 24, 18, 18, 30, 24, 24, 18, 18, 24, 30, 18 };
        var requirements = names.Zip(totals).ToDictionary(x => "/Lotus/Types/Items/MushroomJournal/" + x.First + "MushroomJournalItem", x => x.Second); if (!requirements.ContainsKey(type)) throw new ApiException(400, "Unknown journal mushroom");
        Inventory.AddCount(inv, "MiscItems", type, -count); var changes = new JObject { ["MiscItems"] = new JArray(new JObject { ["ItemType"] = type, ["ItemCount"] = -count }) };
        if (body.Value<bool>("Convert")) { const string food = "/Lotus/Types/Items/MiscItems/MushroomFood"; Inventory.AddCount(inv, "MiscItems", food, count); ((JArray)changes["MiscItems"]!).Add(new JObject { ["ItemType"] = food, ["ItemCount"] = count }); }
        var colony = inv.Obj("NokkoColony"); colony["FeedLevel"] ??= 0; var journal = colony.Array("JournalEntries"); var entry = journal.OfType<JObject>().FirstOrDefault(x => x.Value<string>("EntryType") == type);
        if (entry is null) { entry = new JObject { ["EntryType"] = type, ["Progress"] = 0 }; journal.Add(entry); }
        int Rank() { var completed = journal.Count(x => requirements.TryGetValue(x.Value<string>("EntryType") ?? "", out var required) && x.Value<int>("Progress") >= required); return new[] { 0, 1, 2, 6, 12, 16 }.Count(x => completed >= x) - 1; }
        var previous = Rank(); if (entry.Value<int>("Progress") < requirements[type]) entry["Progress"] = checked(entry.Value<int>("Progress") + count); var next = Rank(); var affiliation = Standing.Affiliation(inv, "NightcapJournalSyndicate"); var mods = new JArray();
        if (next > affiliation.Value<int>("Title")) { affiliation["Title"] = next; mods.Add(new JObject { ["Tag"] = "NightcapJournalSyndicate", ["Title"] = next }); }
        return ApiResponse.Json(new JObject { ["PrevRank"] = previous, ["NewRank"] = next, ["Progress"] = entry["Progress"]!.DeepClone(), ["InventoryChanges"] = changes, ["AffiliationMods"] = mods });
    }
}