diff --git a/KitchenSink/Commands/DropboxQueue.cs b/KitchenSink/Commands/DropboxQueue.cs index c4fd5ca..4f71249 100644 --- a/KitchenSink/Commands/DropboxQueue.cs +++ b/KitchenSink/Commands/DropboxQueue.cs @@ -5,259 +5,299 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Dalamud.Game.Command; +using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game; using LLib; -namespace KitchenSink.Commands +namespace KitchenSink.Commands; + +internal sealed class DropboxQueue : IDisposable { - internal sealed class DropboxQueue : IDisposable + private static readonly InventoryType[] DefaultInventoryTypes = + [ + InventoryType.Inventory1, + InventoryType.Inventory2, + InventoryType.Inventory3, + InventoryType.Inventory4, + InventoryType.Crystals, + InventoryType.Currency, + ]; + + private readonly ICommandManager _commandManager; + private readonly IChatGui _chatGui; + private readonly DropboxApi _dropboxApi; + + public DropboxQueue(DalamudReflector reflector, ICommandManager commandManager, IChatGui chatGui, + IPluginLog pluginLog) { - private static readonly InventoryType[] DefaultInventoryTypes = - [ - InventoryType.Inventory1, - InventoryType.Inventory2, - InventoryType.Inventory3, - InventoryType.Inventory4, - InventoryType.Crystals, - InventoryType.Currency, - ]; + _commandManager = commandManager; + _chatGui = chatGui; + _dropboxApi = new DropboxApi(reflector, pluginLog); - private readonly ICommandManager _commandManager; - private readonly IChatGui _chatGui; - private readonly DropboxApi _dropboxApi; - - public DropboxQueue(DalamudReflector reflector, ICommandManager commandManager, IChatGui chatGui, - IPluginLog pluginLog) + _commandManager.AddHandler("/dbq", new CommandInfo(Queue) { - _commandManager = commandManager; - _chatGui = chatGui; - _dropboxApi = new DropboxApi(reflector, pluginLog); + HelpMessage = + $"Queue items to be imported into dropbox{Environment.NewLine}" + + $"\t/dbq item1:qty1 item2:qty2 [...] - queues items for the next trade (use * as quantity for 'all'){Environment.NewLine}n" + + $"\t/dbq clear - remove all items in the queue{Environment.NewLine}" + + $"\t/dbq request item1:qty1 item2:qty2 [...] - show the command to fill your inventory with the specific item quantities{Environment.NewLine}" + + $"\t/dbq [shards/crystals/shards+crystals] - show the command to fill shards and/or crystals to 9999" + }); + } - _commandManager.AddHandler("/dbq", new CommandInfo(Queue) - { - HelpMessage = - $"Queue items to be imported into dropbox{Environment.NewLine}\t/dbq item1:qty1 item2:qty2 [...] - queues items for the next trade (use * as quantity for 'all'){Environment.NewLine}\t/dbq clear - remove all items in the queue{Environment.NewLine}\t/dbq crystals - show the command to fill all shards & crystals to 9999" - }); - } - - private void Queue(string command, string arguments) + private void Queue(string command, string arguments) + { + string[] parts = arguments.Split(" ", 2); + switch (parts[0]) { - if (arguments == "crystals") - { - ShowCrystals(); - } - else if (arguments == "clear") - { + case "shards": + BuildRequest(string.Join(" ", Enumerable.Range(2, 6).Select(x => $"{x}:9999"))); + break; + case "crystals": + BuildRequest(string.Join(" ", Enumerable.Range(8, 6).Select(x => $"{x}:9999"))); + break; + case "shards+crystals": + BuildRequest(string.Join(" ", Enumerable.Range(2, 12).Select(x => $"{x}:9999"))); + break; + case "request": + BuildRequest(parts.Length == 2 ? parts[1] : string.Empty); + break; + case "clear": _dropboxApi.ClearQueue(); - } - else - { - var parsedItems = arguments.Split(' ') - .Select(x => x.Split(':')) - .Select(x => - { - if (x.Length != 2) - return ($"Unable to parse {string.Join(" ", x)}.", null); + break; + default: + AddToQueue(arguments); + break; + } + } - if (!uint.TryParse(x[0], out uint itemId)) - return ($"Unable to parse item id {x[0]}.", null); - - int needed; - if (x[1] == "*") - needed = int.MaxValue; - else if (!int.TryParse(x[1], out needed)) - return ($"Unable to parse quantity {x[1]}.", null); - - return (string.Empty, new NeededItem(itemId, needed)); - }).ToList(); - if (parsedItems.Count == 0) - return; - - var problematic = parsedItems.Where(x => !string.IsNullOrEmpty(x.Item1)).Select(x => x.Item1).ToList(); - if (problematic.Count == 1) - { - _chatGui.PrintError($"dbq: {problematic.First()}"); - } - else if (problematic.Count >= 2) - { - _chatGui.PrintError("dbq: Multiple errors occured:"); - foreach (string problem in problematic) - _chatGui.PrintError($" - {problem}"); - } - else - { - Dictionary allItems = GetItemCounts(); - foreach (var neededItem in parsedItems.Select(x => x.Item2).Cast()) - { - if (!allItems.TryGetValue(neededItem.ItemId, out ItemCount? itemCount)) - continue; - - int normalQualityQuantity = Math.Min(neededItem.Needed, itemCount.NormalQualityQuantity); - int highQualityQuantity = Math.Min(neededItem.Needed - normalQualityQuantity, - itemCount.HighQualityQuantity); - - if (normalQualityQuantity > 0) - _dropboxApi.EnqueueItem(neededItem.ItemId, false, normalQualityQuantity); - - if (highQualityQuantity > 0) - _dropboxApi.EnqueueItem(neededItem.ItemId, true, highQualityQuantity); - - if (normalQualityQuantity > 0 || highQualityQuantity > 0) - { - allItems[neededItem.ItemId] = - new ItemCount( - itemCount.NormalQualityQuantity - normalQualityQuantity, - itemCount.HighQualityQuantity - highQualityQuantity); - } - } - } - } + private unsafe void BuildRequest(string arguments) + { + if (string.IsNullOrEmpty(arguments)) + { + _chatGui.PrintError("Usage: /dbq request item1:qty1 item2:qty2 [...]"); } - private unsafe Dictionary GetItemCounts() - { - Dictionary allItems = new(); + InventoryManager* inventoryManger = InventoryManager.Instance(); + if (inventoryManger == null) + return; - InventoryManager* inventoryManager = InventoryManager.Instance(); - if (inventoryManager == null) - return allItems; + IReadOnlyList? parsedItems = ParseArguments(arguments); + if (parsedItems == null) + return; - foreach (var type in DefaultInventoryTypes) + var missingItems = parsedItems + .Select(item => item with { - InventoryContainer* container = inventoryManager->GetInventoryContainer(type); - for (int i = 0; i < container->Size; ++i) - { - var item = container->GetInventorySlot(i); - if (item != null && item->ItemID != 0) - { - if (item->Spiritbond > 0) - continue; - - if (!allItems.TryGetValue(item->ItemID, out ItemCount? itemCount)) - itemCount = new(0, 0); - - if (item->Flags.HasFlag(InventoryItem.ItemFlags.HQ)) - itemCount = itemCount with - { - HighQualityQuantity = itemCount.HighQualityQuantity + (int)item->Quantity - }; - else - itemCount = itemCount with - { - NormalQualityQuantity = itemCount.NormalQualityQuantity + (int)item->Quantity - }; - - allItems[item->ItemID] = itemCount; - } - } - } - - return allItems; + Needed = item.Needed - inventoryManger->GetItemCountInContainer(item.ItemId, InventoryType.Crystals) + }) + .Where(x => x.Needed > 0) + .ToList(); + if (missingItems.Count == 0) + { + _chatGui.Print("No items need to be filled"); + return; } - private unsafe void ShowCrystals() + _chatGui.Print(new SeStringBuilder().AddUiForeground("[KitchenSink] ", 504) + .Append($"/dbq {string.Join(" ", missingItems)}").Build()); + } + + private void AddToQueue(string arguments) + { + IReadOnlyList? parsedItems = ParseArguments(arguments); + if (parsedItems == null) + return; + + Dictionary allItems = GetItemCounts(); + foreach (var neededItem in parsedItems) { - InventoryManager* inventoryManger = InventoryManager.Instance(); - if (inventoryManger == null) - return; + if (!allItems.TryGetValue(neededItem.ItemId, out ItemCount? itemCount)) + continue; - var missingCrystals = Enumerable.Range(2, 12).Select(itemId => (uint)itemId) - .Select(itemId => new NeededItem(itemId, - 9999 - inventoryManger->GetItemCountInContainer(itemId, InventoryType.Crystals))) - .Where(x => x.Needed > 0) - .ToList(); - if (missingCrystals.Count == 0) + int normalQualityQuantity = Math.Min(neededItem.Needed, itemCount.NormalQualityQuantity); + int highQualityQuantity = Math.Min(neededItem.Needed - normalQualityQuantity, + itemCount.HighQualityQuantity); + + if (normalQualityQuantity > 0) + _dropboxApi.EnqueueItem(neededItem.ItemId, false, normalQualityQuantity); + + if (highQualityQuantity > 0) + _dropboxApi.EnqueueItem(neededItem.ItemId, true, highQualityQuantity); + + if (normalQualityQuantity > 0 || highQualityQuantity > 0) { - _chatGui.Print("No crystals need to be filled"); - return; - } - - _chatGui.Print($"Command: /dbq {string.Join(" ", missingCrystals)}"); - } - - public void Dispose() - { - _commandManager.RemoveHandler("/dbq"); - } - - private sealed record NeededItem(uint ItemId, int Needed) - { - public override string ToString() => $"{ItemId}:{Needed}"; - } - - private sealed record ItemCount(int NormalQualityQuantity, int HighQualityQuantity); - - private sealed class DropboxApi - { - private readonly DalamudReflector _reflector; - private readonly IPluginLog _pluginLog; - - public DropboxApi(DalamudReflector reflector, IPluginLog pluginLog) - { - _reflector = reflector; - _pluginLog = pluginLog; - } - - [SuppressMessage("Performance", "CA2000", Justification = "Should not dispose other plugin")] - public void EnqueueItem(uint itemId, bool hq, int quantity) - { - _pluginLog.Verbose($"Preparing to queue {itemId}, {hq}, {quantity}"); - if (quantity < 0) - return; - - if (!TryGetItemQuantities(out IDalamudPlugin? dropboxPlugin, out IDictionary? itemQuantities)) - throw new InvalidOperationException("Could not retrieve item quantities"); - - uint[] tradeableItemIds = (uint[])dropboxPlugin.GetType() - .GetField("TradeableItems", BindingFlags.Public | BindingFlags.Instance)! - .GetValue(dropboxPlugin)!; - if (!tradeableItemIds.Contains(itemId)) - { - _pluginLog.Warning($"Item {itemId} is untradable"); - return; - } - - - var itemDescriptorType = itemQuantities.GetType().GetGenericArguments()[0]; - var itemDescriptor = Activator.CreateInstance(itemDescriptorType, args: [itemId, hq])!; - - var queuedQuantity = itemQuantities[itemDescriptor]; - _pluginLog.Verbose($"Retrieved quantity: {queuedQuantity}"); - if (queuedQuantity == null) - return; - - var boxType = queuedQuantity.GetType(); - var valueField = boxType.GetField("Value", BindingFlags.Public | BindingFlags.Instance)!; - - _pluginLog.Information($"Adding {itemDescriptor} to queue"); - valueField.SetValue(queuedQuantity, quantity); - } - - public void ClearQueue() - { - if (!TryGetItemQuantities(out IDalamudPlugin? _, out IDictionary? itemQuantities)) - throw new InvalidOperationException("Could not retrieve item quantities"); - - itemQuantities.Clear(); - } - - private bool TryGetItemQuantities([NotNullWhen(true)] out IDalamudPlugin? dropboxPlugin, - [NotNullWhen(true)] out IDictionary? itemQuantities) - { - if (!_reflector.TryGetDalamudPlugin("Dropbox", out dropboxPlugin)) - { - itemQuantities = null; - return false; - } - - var itemQueueUiType = dropboxPlugin.GetType().Assembly.GetType("Dropbox.ItemQueueUI")!; - itemQuantities = - (IDictionary?)itemQueueUiType.GetField("ItemQuantities", BindingFlags.Public | BindingFlags.Static)! - .GetValue(null); - return itemQuantities != null; + allItems[neededItem.ItemId] = + new ItemCount( + itemCount.NormalQualityQuantity - normalQualityQuantity, + itemCount.HighQualityQuantity - highQualityQuantity); } } } + + private IReadOnlyList? ParseArguments(string arguments) + { + var parsedItems = arguments.Split(' ') + .Select(x => x.Split(':')) + .Select(x => + { + if (x.Length != 2) + return ($"Unable to parse {string.Join(" ", x)}.", null); + + if (!uint.TryParse(x[0], out uint itemId)) + return ($"Unable to parse item id {x[0]}.", null); + + int needed; + if (x[1] == "*") + needed = int.MaxValue; + else if (!int.TryParse(x[1], out needed)) + return ($"Unable to parse quantity {x[1]}.", null); + + return (string.Empty, new NeededItem(itemId, needed)); + }).ToList(); + if (parsedItems.Count == 0) + return null; + + var problematic = parsedItems.Where(x => !string.IsNullOrEmpty(x.Item1)).Select(x => x.Item1).ToList(); + if (problematic.Count == 1) + { + _chatGui.PrintError($"dbq: {problematic.First()}"); + return null; + } + else if (problematic.Count >= 2) + { + _chatGui.PrintError("dbq: Multiple errors occured:"); + foreach (string problem in problematic) + _chatGui.PrintError($" - {problem}"); + return null; + } + else + return parsedItems.Select(x => x.Item2!).ToList().AsReadOnly(); + } + + private unsafe Dictionary GetItemCounts() + { + Dictionary allItems = new(); + + InventoryManager* inventoryManager = InventoryManager.Instance(); + if (inventoryManager == null) + return allItems; + + foreach (var type in DefaultInventoryTypes) + { + InventoryContainer* container = inventoryManager->GetInventoryContainer(type); + for (int i = 0; i < container->Size; ++i) + { + var item = container->GetInventorySlot(i); + if (item != null && item->ItemID != 0) + { + if (item->Spiritbond > 0) + continue; + + if (!allItems.TryGetValue(item->ItemID, out ItemCount? itemCount)) + itemCount = new(0, 0); + + if (item->Flags.HasFlag(InventoryItem.ItemFlags.HQ)) + itemCount = itemCount with + { + HighQualityQuantity = itemCount.HighQualityQuantity + (int)item->Quantity + }; + else + itemCount = itemCount with + { + NormalQualityQuantity = itemCount.NormalQualityQuantity + (int)item->Quantity + }; + + allItems[item->ItemID] = itemCount; + } + } + } + + return allItems; + } + + public void Dispose() + { + _commandManager.RemoveHandler("/dbq"); + } + + private sealed record NeededItem(uint ItemId, int Needed) + { + public override string ToString() => $"{ItemId}:{Needed}"; + } + + private sealed record ItemCount(int NormalQualityQuantity, int HighQualityQuantity); + + private sealed class DropboxApi + { + private readonly DalamudReflector _reflector; + private readonly IPluginLog _pluginLog; + + public DropboxApi(DalamudReflector reflector, IPluginLog pluginLog) + { + _reflector = reflector; + _pluginLog = pluginLog; + } + + [SuppressMessage("Performance", "CA2000", Justification = "Should not dispose other plugin")] + public void EnqueueItem(uint itemId, bool hq, int quantity) + { + _pluginLog.Verbose($"Preparing to queue {itemId}, {hq}, {quantity}"); + if (quantity < 0) + return; + + if (!TryGetItemQuantities(out IDalamudPlugin? dropboxPlugin, out IDictionary? itemQuantities)) + throw new InvalidOperationException("Could not retrieve item quantities"); + + uint[] tradeableItemIds = (uint[])dropboxPlugin.GetType() + .GetField("TradeableItems", BindingFlags.Public | BindingFlags.Instance)! + .GetValue(dropboxPlugin)!; + if (!tradeableItemIds.Contains(itemId)) + { + _pluginLog.Warning($"Item {itemId} is untradable"); + return; + } + + + var itemDescriptorType = itemQuantities.GetType().GetGenericArguments()[0]; + var itemDescriptor = Activator.CreateInstance(itemDescriptorType, args: [itemId, hq])!; + + var queuedQuantity = itemQuantities[itemDescriptor]; + _pluginLog.Verbose($"Retrieved quantity: {queuedQuantity}"); + if (queuedQuantity == null) + return; + + var boxType = queuedQuantity.GetType(); + var valueField = boxType.GetField("Value", BindingFlags.Public | BindingFlags.Instance)!; + + _pluginLog.Information($"Adding {itemDescriptor} to queue"); + valueField.SetValue(queuedQuantity, quantity); + } + + public void ClearQueue() + { + if (!TryGetItemQuantities(out IDalamudPlugin? _, out IDictionary? itemQuantities)) + throw new InvalidOperationException("Could not retrieve item quantities"); + + itemQuantities.Clear(); + } + + private bool TryGetItemQuantities([NotNullWhen(true)] out IDalamudPlugin? dropboxPlugin, + [NotNullWhen(true)] out IDictionary? itemQuantities) + { + if (!_reflector.TryGetDalamudPlugin("Dropbox", out dropboxPlugin)) + { + itemQuantities = null; + return false; + } + + var itemQueueUiType = dropboxPlugin.GetType().Assembly.GetType("Dropbox.ItemQueueUI")!; + itemQuantities = + (IDictionary?)itemQueueUiType.GetField("ItemQuantities", BindingFlags.Public | BindingFlags.Static)! + .GetValue(null); + return itemQuantities != null; + } + } } diff --git a/KitchenSink/KitchenSink.csproj b/KitchenSink/KitchenSink.csproj index 87f197e..808cb74 100644 --- a/KitchenSink/KitchenSink.csproj +++ b/KitchenSink/KitchenSink.csproj @@ -1,7 +1,7 @@  net8.0-windows - 0.3 + 0.4 12 enable true