using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed partial class QuestApi(ItemCatalog catalog, TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["updateQuestController", "giveKeyChainTriggeredItemsController", "giveKeyChainTriggeredMessageController", "giveQuestKeyRewardController", "unlockShipFeatureController"];
private static readonly Lazy<JObject> CompletionItems = new(() => (JObject)Assets.Json("fixed_responses/questCompletionRewards.json"));
public ApiResponse Handle(string controller, JObject account, ApiRequest request)
{
var body = request.ObjectBody(); var inv = account.Obj("Inventory");
switch (controller)
{
case "unlockShipFeatureController": InventoryProgress.UnlockShip(account, body.RequiredString("Feature")); return ApiResponse.Json(new JArray());
case "updateQuestController":
var keys = body["QuestKeys"] as JArray ?? throw new ApiException(400, "Missing QuestKeys");
var response = new JObject { ["MissionRewards"] = new JArray(), ["InventoryChanges"] = Update(account, keys) };
if (keys[0]?["CustomData"] is JToken custom) response["CustomData"] = custom.DeepClone();
return ApiResponse.Json(response);
case "giveQuestKeyRewardController":
var reward = body["reward"] as JObject ?? throw new ApiException(400, "Expected one quest reward");
return ApiResponse.Json(new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("ItemType"), (int)reward.Integer("Amount", 1, 100_000)));
case "giveKeyChainTriggeredItemsController": return ApiResponse.Json(TriggeredItems(account, body));
case "giveKeyChainTriggeredMessageController": TriggeredMessage(account, body); return ApiResponse.Json(1);
default: throw new ApiException(404, "Unknown quest operation");
}
}
public JObject Update(JObject account, JArray uploads)
{
if (uploads.Count != 1 || uploads[0] is not JObject upload) throw new ApiException(400, "Update exactly one quest");
var type = upload.RequiredString("ItemType"); var meta = Meta(type); var inv = account.Obj("Inventory");
var quest = Find(inv, type);
if (upload["Progress"] is not JArray progress || progress.Count > meta.Array("chainStages").Count) throw new ApiException(400, "Invalid quest progress");
foreach (var stage in progress.OfType<JObject>()) stage.Integer("c", -1, 1000);
var run = progress.FirstOrDefault()?.Value<int>("c") ?? 0;
var alreadyCompleted = quest.Value<bool>("Completed") && (quest["Progress"]?.FirstOrDefault()?.Value<int>("c") ?? 0) >= run;
var oldDate = quest["CompletionDate"]?.DeepClone();
quest.RemoveAll();
foreach (var property in upload.Properties()) if (property.Name != "CompletionDate") quest[property.Name] = property.Value.DeepClone();
var changes = new JObject();
if (quest.Value<bool>("Completed"))
{
quest["CompletionDate"] = alreadyCompleted && oldDate is not null ? oldDate : Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds());
var key = $"complete:{type}:{run}";
if (!alreadyCompleted && !account.Array("QuestClaims").Any(x => x.ToString() == key))
{
Complete(account, type, changes, run > 0); account.Array("QuestClaims").Add(key);
}
if (inv.Value<string>("ActiveQuest") == type) inv["ActiveQuest"] = "";
ShipFeatureProgress.RestoreCompletedQuests(account);
}
return changes;
}
private static JObject Meta(string type) => GameData.Find("Keys", type) is JObject meta && meta["chainStages"] is JArray ? meta : throw new ApiException(400, "Unknown quest key chain");
private static JObject Find(JObject inv, string type) => inv.Array("QuestKeys").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type) ?? throw new ApiException(404, "Quest key not owned");
private static (JObject Quest, JObject Stage, JObject Meta, int Index, string Claim) Stage(JObject account, JObject body, string kind)
{
var type = body.RequiredString("KeyChain"); var meta = Meta(type); var index = (int)body.Integer("ChainStage", 0, meta.Array("chainStages").Count - 1);
var quest = Find(account.Obj("Inventory"), type); var progress = quest.Array("Progress");
if (index > progress.Count) throw new ApiException(409, "Previous quest stages are missing");
if (index == progress.Count) progress.Add(new JObject { ["c"] = -1, ["i"] = false, ["m"] = false, ["b"] = new JArray() });
var run = Math.Max(0, progress[0]!.Value<int>("c"));
return (quest, (JObject)progress[index], meta, index, $"{kind}:{type}:{run}:{index}");
}
private JObject TriggeredItems(JObject account, JObject body)
{
var info = Stage(account, body, "items"); var changes = new JObject();
if (info.Stage.Value<bool>("i") || account.Array("QuestClaims").Any(x => x.ToString() == info.Claim)) return changes;
var acquire = new ItemAcquisition(catalog, clock, account);
foreach (var type in info.Meta["chainStages"]![info.Index]!["itemsToGiveWhenTriggered"] as JArray ?? [])
Inventory.Combine(changes, acquire.Add(account.Obj("Inventory"), type.ToString()));
info.Stage["i"] = true; account.Array("QuestClaims").Add(info.Claim); return changes;
}
private void TriggeredMessage(JObject account, JObject body)
{
var info = Stage(account, body, "message");
if (info.Stage.Value<bool>("m") || account.Array("QuestClaims").Any(x => x.ToString() == info.Claim)) return;
var message = info.Meta.Array("chainStages").Skip(info.Index).Select(x => x["messageToSendWhenTriggered"] as JObject).FirstOrDefault(x => x is not null)
?? throw new ApiException(400, "Quest stage has no message");
var template = InboxApi.FromExport(message);
if ((info.Quest["Progress"]?[0]?.Value<int>("c") ?? 0) > 0) { template["att"] = new JArray(); template["countedAtt"] = new JArray(); }
InboxApi.Create(account, template, clock.GetUtcNow()); info.Stage["m"] = true; account.Array("QuestClaims").Add(info.Claim);
}
private void Complete(JObject account, string type, JObject changes, bool rerun)
{
var inv = account.Obj("Inventory"); var acquire = new ItemAcquisition(catalog, clock, account);
if (type == "/Lotus/Types/Keys/OrokinMoonQuest/OrokinMoonQuestKeyChain")
InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Bosses/Ordis", ["msg"] = "/Lotus/Language/G1Quests/SecondDreamFinishInboxMessage", ["sub"] = "/Lotus/Language/G1Quests/SecondDreamFinishInboxTitle", ["icon"] = "/Lotus/Interface/Icons/Npcs/Ordis.png", ["highPriority"] = true, ["att"] = rerun ? new JArray() : new JArray("/Lotus/Weapons/Tenno/Melee/Swords/StalkerTwo/StalkerTwoSmallSword", "/Lotus/Upgrades/Skins/Sigils/ScarSigil") }, clock.GetUtcNow());
if (rerun) return;
if (type == "/Lotus/Types/Keys/DragonQuest/DragonQuestKeyChain")
{
var affiliation = inv.Array("Affiliations").OfType<JObject>().FirstOrDefault(x => x.Value<string>("Tag") == "LibrarySyndicate");
if (affiliation is null) { affiliation = new JObject { ["Tag"] = "LibrarySyndicate", ["Standing"] = 0, ["Title"] = 0 }; inv.Array("Affiliations").Add(affiliation); }
if (!affiliation.Value<bool>("Initiated")) { Inventory.Combine(changes, acquire.Add(inv, "/Lotus/Types/StoreItems/Packages/SanctuaryInitiationKit")); affiliation["Initiated"] = true; }
}
if (type == "/Lotus/Types/Keys/NewWarQuest/NewWarQuestKeyChain" && !inv.Array("Affiliations").Any(x => x.Value<string>("Tag") == "KahlSyndicate"))
inv.Array("Affiliations").Add(new JObject { ["Tag"] = "KahlSyndicate", ["Title"] = 1, ["Standing"] = 1, ["WeeklyMissions"] = new JArray(new JObject { ["MissionIndex"] = 0, ["CompletedMission"] = false, ["JobManifest"] = "/Lotus/Syndicates/Kahl/KahlJobManifestVersionThree", ["WeekCount"] = (clock.GetUtcNow().ToUnixTimeMilliseconds() - 1391990400000L) / 604800000, ["Challenges"] = new JArray() }) });
bool Finishes(params string[] quests) => quests.Contains(type) && quests.All(q => inv.Array("QuestKeys").Any(x => x.Value<string>("ItemType") == q && x.Value<bool>("Completed")));
if (Finishes("/Lotus/Types/Keys/NewWarQuest/NewWarQuestKeyChain", "/Lotus/Types/Keys/InfestedMicroplanetQuest/InfestedMicroplanetQuestKeyChain"))
InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Bosses/Loid", ["msg"] = "/Lotus/Language/EntratiLab/EntratiQuest/WiTWQuestRecievedInboxBody", ["sub"] = "/Lotus/Language/EntratiLab/EntratiQuest/WiTWQuestRecievedInboxTitle", ["icon"] = "/Lotus/Interface/Icons/Npcs/Entrati/Loid.png", ["highPriority"] = true, ["att"] = new JArray("/Lotus/Types/Keys/EntratiLab/EntratiQuestKeyChain") }, clock.GetUtcNow());
if (Finishes("/Lotus/Types/Keys/1999PrologueQuest/1999PrologueQuestKeyChain", "/Lotus/Types/Keys/DuviriQuest/DuviriQuestKeyChain"))
Inventory.Combine(changes, acquire.Add(inv, "/Lotus/Types/Items/EmailItems/1999QuestEmailItem"));
if (CompletionItems.Value[type] is JArray items)
foreach (var reward in items.OfType<JObject>()) Inventory.Combine(changes, acquire.Add(inv, reward.RequiredString("ItemType"), (int)reward.Integer("ItemCount", 1, 100_000)));
else foreach (var reward in Meta(type)["rewards"] as JArray ?? [])
{
var kind = reward.Value<string>("rewardType");
if (kind is "RT_RESOURCE" or "RT_RECIPE" or "RT_STORE_ITEM")
Inventory.Combine(changes, acquire.Add(inv, reward.Value<string>("itemType")!, kind == "RT_STORE_ITEM" ? 1 : reward.Value<int>("amount")));
}
}
}
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
public sealed partial class QuestApi(ItemCatalog catalog, TimeProvider clock)
{
public static readonly HashSet<string> Controllers = ["updateQuestController", "giveKeyChainTriggeredItemsController", "giveKeyChainTriggeredMessageController", "giveQuestKeyRewardController", "unlockShipFeatureController"];
private static readonly Lazy<JObject> CompletionItems = new(() => (JObject)Assets.Json("fixed_responses/questCompletionRewards.json"));
public ApiResponse Handle(string controller, JObject account, ApiRequest request)
{
var body = request.ObjectBody(); var inv = account.Obj("Inventory");
switch (controller)
{
case "unlockShipFeatureController": InventoryProgress.UnlockShip(account, body.RequiredString("Feature")); return ApiResponse.Json(new JArray());
case "updateQuestController":
var keys = body["QuestKeys"] as JArray ?? throw new ApiException(400, "Missing QuestKeys");
var response = new JObject { ["MissionRewards"] = new JArray(), ["InventoryChanges"] = Update(account, keys) };
if (keys[0]?["CustomData"] is JToken custom) response["CustomData"] = custom.DeepClone();
return ApiResponse.Json(response);
case "giveQuestKeyRewardController":
var reward = body["reward"] as JObject ?? throw new ApiException(400, "Expected one quest reward");
return ApiResponse.Json(new ItemAcquisition(catalog, clock, account).Add(inv, reward.RequiredString("ItemType"), (int)reward.Integer("Amount", 1, 100_000)));
case "giveKeyChainTriggeredItemsController": return ApiResponse.Json(TriggeredItems(account, body));
case "giveKeyChainTriggeredMessageController": TriggeredMessage(account, body); return ApiResponse.Json(1);
default: throw new ApiException(404, "Unknown quest operation");
}
}
public JObject Update(JObject account, JArray uploads)
{
if (uploads.Count != 1 || uploads[0] is not JObject upload) throw new ApiException(400, "Update exactly one quest");
var type = upload.RequiredString("ItemType"); var meta = Meta(type); var inv = account.Obj("Inventory");
var quest = Find(inv, type);
if (upload["Progress"] is not JArray progress || progress.Count > meta.Array("chainStages").Count) throw new ApiException(400, "Invalid quest progress");
foreach (var stage in progress.OfType<JObject>()) stage.Integer("c", -1, 1000);
var run = progress.FirstOrDefault()?.Value<int>("c") ?? 0;
var alreadyCompleted = quest.Value<bool>("Completed") && (quest["Progress"]?.FirstOrDefault()?.Value<int>("c") ?? 0) >= run;
var oldDate = quest["CompletionDate"]?.DeepClone();
quest.RemoveAll();
foreach (var property in upload.Properties()) if (property.Name != "CompletionDate") quest[property.Name] = property.Value.DeepClone();
var changes = new JObject();
if (quest.Value<bool>("Completed"))
{
quest["CompletionDate"] = alreadyCompleted && oldDate is not null ? oldDate : Wire.Date(clock.GetUtcNow().ToUnixTimeMilliseconds());
var key = $"complete:{type}:{run}";
if (!alreadyCompleted && !account.Array("QuestClaims").Any(x => x.ToString() == key))
{
Complete(account, type, changes, run > 0); account.Array("QuestClaims").Add(key);
}
if (inv.Value<string>("ActiveQuest") == type) inv["ActiveQuest"] = "";
ShipFeatureProgress.RestoreCompletedQuests(account);
}
return changes;
}
private static JObject Meta(string type) => GameData.Find("Keys", type) is JObject meta && meta["chainStages"] is JArray ? meta : throw new ApiException(400, "Unknown quest key chain");
private static JObject Find(JObject inv, string type) => inv.Array("QuestKeys").OfType<JObject>().FirstOrDefault(x => x.Value<string>("ItemType") == type) ?? throw new ApiException(404, "Quest key not owned");
private static (JObject Quest, JObject Stage, JObject Meta, int Index, string Claim) Stage(JObject account, JObject body, string kind)
{
var type = body.RequiredString("KeyChain"); var meta = Meta(type); var index = (int)body.Integer("ChainStage", 0, meta.Array("chainStages").Count - 1);
var quest = Find(account.Obj("Inventory"), type); var progress = quest.Array("Progress");
if (index > progress.Count) throw new ApiException(409, "Previous quest stages are missing");
if (index == progress.Count) progress.Add(new JObject { ["c"] = -1, ["i"] = false, ["m"] = false, ["b"] = new JArray() });
var run = Math.Max(0, progress[0]!.Value<int>("c"));
return (quest, (JObject)progress[index], meta, index, $"{kind}:{type}:{run}:{index}");
}
private JObject TriggeredItems(JObject account, JObject body)
{
var info = Stage(account, body, "items"); var changes = new JObject();
if (info.Stage.Value<bool>("i") || account.Array("QuestClaims").Any(x => x.ToString() == info.Claim)) return changes;
var acquire = new ItemAcquisition(catalog, clock, account);
foreach (var type in info.Meta["chainStages"]![info.Index]!["itemsToGiveWhenTriggered"] as JArray ?? [])
Inventory.Combine(changes, acquire.Add(account.Obj("Inventory"), type.ToString()));
info.Stage["i"] = true; account.Array("QuestClaims").Add(info.Claim); return changes;
}
private void TriggeredMessage(JObject account, JObject body)
{
var info = Stage(account, body, "message");
if (info.Stage.Value<bool>("m") || account.Array("QuestClaims").Any(x => x.ToString() == info.Claim)) return;
var message = info.Meta.Array("chainStages").Skip(info.Index).Select(x => x["messageToSendWhenTriggered"] as JObject).FirstOrDefault(x => x is not null)
?? throw new ApiException(400, "Quest stage has no message");
var template = InboxApi.FromExport(message);
if ((info.Quest["Progress"]?[0]?.Value<int>("c") ?? 0) > 0) { template["att"] = new JArray(); template["countedAtt"] = new JArray(); }
InboxApi.Create(account, template, clock.GetUtcNow()); info.Stage["m"] = true; account.Array("QuestClaims").Add(info.Claim);
}
private void Complete(JObject account, string type, JObject changes, bool rerun)
{
var inv = account.Obj("Inventory"); var acquire = new ItemAcquisition(catalog, clock, account);
if (type == "/Lotus/Types/Keys/OrokinMoonQuest/OrokinMoonQuestKeyChain")
InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Bosses/Ordis", ["msg"] = "/Lotus/Language/G1Quests/SecondDreamFinishInboxMessage", ["sub"] = "/Lotus/Language/G1Quests/SecondDreamFinishInboxTitle", ["icon"] = "/Lotus/Interface/Icons/Npcs/Ordis.png", ["highPriority"] = true, ["att"] = rerun ? new JArray() : new JArray("/Lotus/Weapons/Tenno/Melee/Swords/StalkerTwo/StalkerTwoSmallSword", "/Lotus/Upgrades/Skins/Sigils/ScarSigil") }, clock.GetUtcNow());
if (rerun) return;
if (type == "/Lotus/Types/Keys/DragonQuest/DragonQuestKeyChain")
{
var affiliation = inv.Array("Affiliations").OfType<JObject>().FirstOrDefault(x => x.Value<string>("Tag") == "LibrarySyndicate");
if (affiliation is null) { affiliation = new JObject { ["Tag"] = "LibrarySyndicate", ["Standing"] = 0, ["Title"] = 0 }; inv.Array("Affiliations").Add(affiliation); }
if (!affiliation.Value<bool>("Initiated")) { Inventory.Combine(changes, acquire.Add(inv, "/Lotus/Types/StoreItems/Packages/SanctuaryInitiationKit")); affiliation["Initiated"] = true; }
}
if (type == "/Lotus/Types/Keys/NewWarQuest/NewWarQuestKeyChain" && !inv.Array("Affiliations").Any(x => x.Value<string>("Tag") == "KahlSyndicate"))
inv.Array("Affiliations").Add(new JObject { ["Tag"] = "KahlSyndicate", ["Title"] = 1, ["Standing"] = 1, ["WeeklyMissions"] = new JArray(new JObject { ["MissionIndex"] = 0, ["CompletedMission"] = false, ["JobManifest"] = "/Lotus/Syndicates/Kahl/KahlJobManifestVersionThree", ["WeekCount"] = (clock.GetUtcNow().ToUnixTimeMilliseconds() - 1391990400000L) / 604800000, ["Challenges"] = new JArray() }) });
bool Finishes(params string[] quests) => quests.Contains(type) && quests.All(q => inv.Array("QuestKeys").Any(x => x.Value<string>("ItemType") == q && x.Value<bool>("Completed")));
if (Finishes("/Lotus/Types/Keys/NewWarQuest/NewWarQuestKeyChain", "/Lotus/Types/Keys/InfestedMicroplanetQuest/InfestedMicroplanetQuestKeyChain"))
InboxApi.Create(account, new JObject { ["sndr"] = "/Lotus/Language/Bosses/Loid", ["msg"] = "/Lotus/Language/EntratiLab/EntratiQuest/WiTWQuestRecievedInboxBody", ["sub"] = "/Lotus/Language/EntratiLab/EntratiQuest/WiTWQuestRecievedInboxTitle", ["icon"] = "/Lotus/Interface/Icons/Npcs/Entrati/Loid.png", ["highPriority"] = true, ["att"] = new JArray("/Lotus/Types/Keys/EntratiLab/EntratiQuestKeyChain") }, clock.GetUtcNow());
if (Finishes("/Lotus/Types/Keys/1999PrologueQuest/1999PrologueQuestKeyChain", "/Lotus/Types/Keys/DuviriQuest/DuviriQuestKeyChain"))
Inventory.Combine(changes, acquire.Add(inv, "/Lotus/Types/Items/EmailItems/1999QuestEmailItem"));
if (CompletionItems.Value[type] is JArray items)
foreach (var reward in items.OfType<JObject>()) Inventory.Combine(changes, acquire.Add(inv, reward.RequiredString("ItemType"), (int)reward.Integer("ItemCount", 1, 100_000)));
else foreach (var reward in Meta(type)["rewards"] as JArray ?? [])
{
var kind = reward.Value<string>("rewardType");
if (kind is "RT_RESOURCE" or "RT_RECIPE" or "RT_STORE_ITEM")
Inventory.Combine(changes, acquire.Add(inv, reward.Value<string>("itemType")!, kind == "RT_STORE_ITEM" ? 1 : reward.Value<int>("amount")));
}
}
}