moved helpers to primary ctor

This commit is contained in:
CWX
2025-01-18 20:11:08 +00:00
parent 9b60f10725
commit 3402f94398
25 changed files with 457 additions and 730 deletions
+16 -43
View File
@@ -13,47 +13,20 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class BotGeneratorHelper
public class BotGeneratorHelper(
ISptLogger<BotGeneratorHelper> _logger,
RandomUtil _randomUtil,
DurabilityLimitsHelper _durabilityLimitsHelper,
ItemHelper _itemHelper,
InventoryHelper _inventoryHelper,
ContainerHelper _containerHelper,
ApplicationContext _applicationContext,
LocalisationService _localisationService,
ConfigServer _configServer
)
{
private readonly ISptLogger<BotGeneratorHelper> _logger;
private readonly RandomUtil _randomUtil;
private readonly DurabilityLimitsHelper _durabilityLimitsHelper;
private readonly ItemHelper _itemHelper;
private readonly InventoryHelper _inventoryHelper;
private readonly ContainerHelper _containerHelper;
private readonly ApplicationContext _applicationContext;
private readonly LocalisationService _localisationService;
private readonly ConfigServer _configServer;
private readonly BotConfig _botConfig;
private readonly PmcConfig _pmcConfig;
public BotGeneratorHelper
(
ISptLogger<BotGeneratorHelper> logger,
RandomUtil randomUtil,
DurabilityLimitsHelper durabilityLimitsHelper,
ItemHelper itemHelper,
InventoryHelper inventoryHelper,
ContainerHelper containerHelper,
ApplicationContext applicationContext,
LocalisationService localisationService,
ConfigServer configServer
)
{
_logger = logger;
_randomUtil = randomUtil;
_durabilityLimitsHelper = durabilityLimitsHelper;
_itemHelper = itemHelper;
_inventoryHelper = inventoryHelper;
_containerHelper = containerHelper;
_applicationContext = applicationContext;
_localisationService = localisationService;
_configServer = configServer;
_botConfig = _configServer.GetConfig<BotConfig>();
_pmcConfig = _configServer.GetConfig<PmcConfig>();
}
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected PmcConfig _pmcConfig = _configServer.GetConfig<PmcConfig>();
/// <summary>
/// Adds properties to an item
@@ -98,8 +71,8 @@ public class BotGeneratorHelper
if (itemTemplate?.Properties?.WeapFireType?.Count == 0)
{
itemProperties.FireMode = itemTemplate.Properties.WeapFireType.Contains("fullauto")
? new UpdFireMode { FireMode = "fullauto" }
itemProperties.FireMode = itemTemplate.Properties.WeapFireType.Contains("fullauto")
? new UpdFireMode { FireMode = "fullauto" }
: new UpdFireMode { FireMode = _randomUtil.GetArrayValue(itemTemplate.Properties.WeapFireType) };
}
@@ -159,7 +132,7 @@ public class BotGeneratorHelper
// Togglable face shield
if (!(itemTemplate?.Properties?.HasHinge ?? false) || !(itemTemplate.Properties.FaceShieldComponent ?? false)) return itemProperties;
// Get chance from botconfig for bot type, use 75% if no value found
var faceShieldActiveChance = GetBotEquipmentSettingFromConfig(
botRole,
+14 -28
View File
@@ -13,34 +13,17 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class BotHelper
public class BotHelper(
ISptLogger<BotHelper> _logger,
DatabaseService _databaseService,
RandomUtil _randomUtil,
ConfigServer _configServer
)
{
protected ISptLogger<BotHelper> _logger;
protected DatabaseService _databaseService;
protected RandomUtil _randomUtil;
protected ConfigServer _configServer;
protected BotConfig _botConfig;
protected PmcConfig _pmcConfig;
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected PmcConfig _pmcConfig = _configServer.GetConfig<PmcConfig>();
protected List<string?> _pmcNames = ["usec", "bear", "pmc", "pmcbear", "pmcusec"];
public BotHelper
(
ISptLogger<BotHelper> logger,
DatabaseService databaseService,
RandomUtil randomUtil,
ConfigServer configServer
)
{
_logger = logger;
_databaseService = databaseService;
_randomUtil = randomUtil;
_configServer = configServer;
_botConfig = configServer.GetConfig<BotConfig>();
_pmcConfig = configServer.GetConfig<PmcConfig>();
}
/// <summary>
/// Get a template object for the specified botRole from bots.types db
/// </summary>
@@ -193,7 +176,7 @@ public class BotHelper
{
if (_pmcConfig.BearType.ToLower() == botRole.ToLower())
return "Bear";
if (_pmcConfig.UsecType.ToLower() == botRole.ToLower())
return "Usec";
@@ -220,8 +203,11 @@ public class BotHelper
var randomType = (side is not null) ? side : (_randomUtil.GetInt(0, 1) == 0) ? "usec" : "bear";
var allNames = _databaseService.GetBots().Types[randomType.ToLower()].FirstNames;
var filteredNames = allNames.Where((name) => name.Length <= maxLength);
if (filteredNames.Count() == 0) {
_logger.Warning($"Unable to filter: {randomType} PMC names to only those under: {maxLength}, none found that match that criteria, selecting from entire name pool instead`,\n");
if (filteredNames.Count() == 0)
{
_logger.Warning(
$"Unable to filter: {randomType} PMC names to only those under: {maxLength}, none found that match that criteria, selecting from entire name pool instead`,\n"
);
return _randomUtil.GetStringCollectionValue(allNames);
}
+25 -41
View File
@@ -10,41 +10,19 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class BotWeaponGeneratorHelper
public class BotWeaponGeneratorHelper(
ISptLogger<BotWeaponGeneratorHelper> _logger,
DatabaseServer _databaseServer,
ItemHelper _itemHelper,
RandomUtil _randomUtil,
HashUtil _hashUtil,
WeightedRandomHelper _weightedRandomHelper,
BotGeneratorHelper _botGeneratorHelper,
LocalisationService _localisationService
)
{
private readonly ISptLogger<BotWeaponGeneratorHelper> _logger;
private readonly DatabaseServer _databaseServer;
private readonly ItemHelper _itemHelper;
private readonly RandomUtil _randomUtil;
private readonly HashUtil _hashUtil;
private readonly WeightedRandomHelper _weightedRandomHelper;
private readonly BotGeneratorHelper _botGeneratorHelper;
private readonly LocalisationService _localisationService;
private readonly List<string> _magCheck = ["CylinderMagazine", "SpringDrivenCylinder"];
public BotWeaponGeneratorHelper
(
ISptLogger<BotWeaponGeneratorHelper> logger,
DatabaseServer databaseServer,
ItemHelper itemHelper,
RandomUtil randomUtil,
HashUtil hashUtil,
WeightedRandomHelper weightedRandomHelper,
BotGeneratorHelper botGeneratorHelper,
LocalisationService localisationService
)
{
_logger = logger;
_databaseServer = databaseServer;
_itemHelper = itemHelper;
_randomUtil = randomUtil;
_hashUtil = hashUtil;
_weightedRandomHelper = weightedRandomHelper;
_botGeneratorHelper = botGeneratorHelper;
_localisationService = localisationService;
}
/// <summary>
/// Get a randomized number of bullets for a specific magazine
/// </summary>
@@ -134,14 +112,18 @@ public class BotWeaponGeneratorHelper
{
if (equipmentSlotsToAddTo is null)
equipmentSlotsToAddTo = [EquipmentSlots.TacticalVest, EquipmentSlots.Pockets];
var ammoItems = _itemHelper.SplitStack(new () {
Id = _hashUtil.Generate(),
Template = ammoTpl,
Upd = new () { StackObjectsCount = cartridgeCount },
});
foreach (var ammoItem in ammoItems) {
var ammoItems = _itemHelper.SplitStack(
new()
{
Id = _hashUtil.Generate(),
Template = ammoTpl,
Upd = new() { StackObjectsCount = cartridgeCount },
}
);
foreach (var ammoItem in ammoItems)
{
var result = _botGeneratorHelper.AddItemWithChildrenToEquipmentSlot(
equipmentSlotsToAddTo,
ammoItem.Id,
@@ -150,10 +132,12 @@ public class BotWeaponGeneratorHelper
inventory
);
if (result != ItemAddedResult.SUCCESS) {
if (result != ItemAddedResult.SUCCESS)
{
_logger.Debug($"Unable to add ammo: {ammoItem.Template} to bot inventory, {result.ToString()}");
if (result == ItemAddedResult.NO_SPACE || result == ItemAddedResult.NO_CONTAINERS) {
if (result == ItemAddedResult.NO_SPACE || result == ItemAddedResult.NO_CONTAINERS)
{
// If there's no space for 1 stack or no containers to hold item, there's no space for the others
break;
}
+6 -14
View File
@@ -7,21 +7,13 @@ using Core.Services;
namespace Core.Helpers.Dialogue;
public abstract class AbstractDialogChatBot : IDialogueChatBot
public abstract class AbstractDialogChatBot(
ISptLogger<AbstractDialogChatBot> _logger,
MailSendService _mailSendService,
IEnumerable<IChatCommand> chatCommands
) : IDialogueChatBot
{
protected ISptLogger<AbstractDialogChatBot> _logger;
protected MailSendService _mailSendService;
private readonly List<IChatCommand> _chatCommands;
public AbstractDialogChatBot(
ISptLogger<AbstractDialogChatBot> logger,
MailSendService mailSendService,
IEnumerable<IChatCommand> chatCommands)
{
_logger = logger;
_mailSendService = mailSendService;
_chatCommands = chatCommands.ToList();
}
protected List<IChatCommand> _chatCommands = chatCommands.ToList();
public abstract UserDialogInfo GetChatBot();
+7 -13
View File
@@ -10,20 +10,14 @@ using Core.Services;
namespace Core.Helpers.Dialogue;
[Injectable]
public class CommandoDialogChatBot : AbstractDialogChatBot
public class CommandoDialogChatBot(
ISptLogger<AbstractDialogChatBot> logger,
MailSendService mailSendService,
ConfigServer _configServer,
IEnumerable<IChatCommand> chatCommands
) : AbstractDialogChatBot(logger, mailSendService, chatCommands)
{
protected ConfigServer _configServer;
protected CoreConfig _coreConfig;
public CommandoDialogChatBot(
ISptLogger<AbstractDialogChatBot> logger,
MailSendService mailSendService,
ConfigServer configServer,
IEnumerable<IChatCommand> chatCommands): base(logger, mailSendService, chatCommands)
{
_configServer = configServer;
_coreConfig = _configServer.GetConfig<CoreConfig>();
}
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
public override UserDialogInfo GetChatBot()
{
+7 -17
View File
@@ -11,24 +11,14 @@ using Core.Services;
namespace Core.Helpers.Dialogue;
[Injectable]
public class SptDialogueChatBot : AbstractDialogChatBot
public class SptDialogueChatBot(
ISptLogger<AbstractDialogChatBot> _logger,
MailSendService mailSendService,
IEnumerable<IChatCommand> chatCommands,
ConfigServer configServer
) : AbstractDialogChatBot(_logger, mailSendService, chatCommands)
{
protected ISptLogger<AbstractDialogChatBot> _logger;
protected ConfigServer _configServer;
protected CoreConfig _coreConfig;
public SptDialogueChatBot(
ISptLogger<AbstractDialogChatBot> logger,
MailSendService mailSendService,
IEnumerable<IChatCommand> chatCommands,
ConfigServer configServer
) : base(logger, mailSendService, chatCommands)
{
_logger = logger;
_configServer = configServer;
_coreConfig = configServer.GetConfig<CoreConfig>();
}
protected CoreConfig _coreConfig = configServer.GetConfig<CoreConfig>();
public override UserDialogInfo GetChatBot()
{
+19 -40
View File
@@ -10,38 +10,17 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class DialogueHelper
public class DialogueHelper(
ISptLogger<DialogueHelper> _logger,
HashUtil _hashUtil,
SaveServer _saveServer,
DatabaseServer _databaseServer,
NotifierHelper _notifierHelper,
NotificationSendHelper _notificationSendHelper,
LocalisationService _localisationService,
ItemHelper _itemHelper
)
{
protected ISptLogger<DialogueHelper> _logger;
protected HashUtil _hashUtil;
protected SaveServer _saveServer;
protected DatabaseServer _databaseServer;
protected NotifierHelper _notifierHelper;
protected NotificationSendHelper _notificationSendHelper;
protected LocalisationService _localisationService;
protected ItemHelper _itemHelper;
public DialogueHelper
(
ISptLogger<DialogueHelper> logger,
HashUtil hashUtil,
SaveServer saveServer,
DatabaseServer databaseServer,
NotifierHelper notifierHelper,
NotificationSendHelper notificationSendHelper,
LocalisationService localisationService,
ItemHelper itemHelper
)
{
_logger = logger;
_hashUtil = hashUtil;
_saveServer = saveServer;
_databaseServer = databaseServer;
_notifierHelper = notifierHelper;
_localisationService = localisationService;
_itemHelper = itemHelper;
}
/// <summary>
/// Get the preview contents of the last message in a dialogue.
/// </summary>
@@ -58,13 +37,13 @@ public class DialogueHelper
TemplateId = message?.TemplateId,
UserId = dialogue?.Id
};
if (message?.Text is not null)
result.Text = message.Text;
if (message?.SystemData is not null)
result.SystemData = message?.SystemData;
return result;
}
@@ -89,7 +68,7 @@ public class DialogueHelper
var attachmentsNew = _saveServer.GetProfile(sessionID).DialogueRecords[dialogue.Key].AttachmentsNew;
if (attachmentsNew > 0)
_saveServer.GetProfile(sessionID).DialogueRecords[dialogue.Key].AttachmentsNew = attachmentsNew - 1;
// Check reward count when item being moved isn't in reward list
// If count is 0, it means after this move occurs the reward array will be empty and all rewards collected
if (message.Items.Data is null)
@@ -101,11 +80,11 @@ public class DialogueHelper
message.RewardCollected = true;
message.HasRewards = false;
}
return message.Items.Data;
}
}
return new List<Item>();
}
@@ -119,7 +98,7 @@ public class DialogueHelper
var profile = _saveServer.GetProfile(sessionId);
if (profile.DialogueRecords is null)
profile.DialogueRecords = new();
return profile.DialogueRecords;
}
@@ -132,10 +111,10 @@ public class DialogueHelper
{
if (dialogue.Id == dialogueId)
returnDialogue = dialogue;
break;
}
return returnDialogue;
}
}
+7 -18
View File
@@ -11,22 +11,12 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class HideoutHelper
public class HideoutHelper(
ISptLogger<HideoutHelper> _logger,
TimeUtil _timeUtil,
LocalisationService _localisationService
)
{
private readonly ISptLogger<HideoutHelper> _logger;
protected TimeUtil _timeUtil;
private readonly LocalisationService _localisationService;
public HideoutHelper(
ISptLogger<HideoutHelper> logger,
TimeUtil timeUtil,
LocalisationService localisationService)
{
_logger = logger;
_timeUtil = timeUtil;
_localisationService = localisationService;
}
/// <summary>
/// Add production to profiles' Hideout.Production array
/// </summary>
@@ -510,9 +500,8 @@ public class HideoutHelper
continue;
}
if (improvementDetails.Completed == false
&& improvementDetails.ImproveCompleteTimestamp < _timeUtil.GetTimeStamp()
)
if (improvementDetails.Completed == false && improvementDetails.ImproveCompleteTimestamp < _timeUtil.GetTimeStamp()
)
{
improvementDetails.Completed = true;
}
+2 -7
View File
@@ -7,9 +7,9 @@ using Core.Servers;
namespace Core.Helpers;
[Injectable(InjectionType.Singleton)]
public class HttpServerHelper
public class HttpServerHelper(ConfigServer configServer)
{
protected HttpConfig _httpConfig;
protected HttpConfig _httpConfig = configServer.GetConfig<HttpConfig>();
protected Dictionary<string, string> mime = new()
{
@@ -24,11 +24,6 @@ public class HttpServerHelper
{ "txt", "text/plain" }
};
public HttpServerHelper(ConfigServer configServer)
{
_httpConfig = configServer.GetConfig<HttpConfig>();
}
public string GetMimeText(string key)
{
return mime[key];
+26 -29
View File
@@ -12,26 +12,13 @@ using Core.Services;
namespace Core.Helpers;
[Injectable]
public class InventoryHelper
public class InventoryHelper(
ISptLogger<InventoryHelper> _logger,
ProfileHelper _profileHelper,
DialogueHelper _dialogueHelper,
LocalisationService _localisationService
)
{
protected ISptLogger<InventoryHelper> _logger;
protected ProfileHelper _profileHelper;
protected DialogueHelper _dialogueHelper;
protected LocalisationService _localisationService;
public InventoryHelper(
ISptLogger<InventoryHelper> logger,
ProfileHelper profileHelper,
DialogueHelper dialogueHelper,
LocalisationService localisationService
)
{
_logger = logger;
_profileHelper = profileHelper;
_dialogueHelper = dialogueHelper;
_localisationService = localisationService;
}
/// <summary>
/// Add multiple items to player stash (assuming they all fit)
/// </summary>
@@ -299,7 +286,8 @@ public class InventoryHelper
// From and To types match, same inventory
var movingToSameInventory = fromType == toType;
return new OwnerInventoryItems{
return new OwnerInventoryItems
{
From = fromInventoryItems,
To = toInventoryItems,
SameInventory = movingToSameInventory,
@@ -391,24 +379,30 @@ public class InventoryHelper
var matchingInventoryItem = inventoryItems.FirstOrDefault((item) => item.Id == moveRequest.Item);
if (matchingInventoryItem is null)
{
var noMatchingItemMesage = $"Unable to move item: { moveRequest.Item}, cannot find in inventory";
var noMatchingItemMesage = $"Unable to move item: {moveRequest.Item}, cannot find in inventory";
_logger.Error(noMatchingItemMesage);
errorMessage = noMatchingItemMesage;
return false;
}
_logger.Debug("${ moveRequest.Action} item: ${ moveRequest.item} from slotid: ${ matchingInventoryItem.slotId} to container: ${ moveRequest.to.container}");
_logger.Debug(
"${ moveRequest.Action} item: ${ moveRequest.item} from slotid: ${ matchingInventoryItem.slotId} to container: ${ moveRequest.to.container}"
);
// Don't move shells from camora to cartridges (happens when loading shells into mts-255 revolver shotgun)
if (matchingInventoryItem.SlotId?.Contains("camora_") is null && moveRequest.To.Container == "cartridges")
{
_logger.Warning(
_localisationService.GetText("inventory-invalid_move_to_container",
new {
_localisationService.GetText(
"inventory-invalid_move_to_container",
new
{
slotId = matchingInventoryItem.SlotId,
container = moveRequest.To.Container,
}));
}
)
);
return true;
}
@@ -421,9 +415,11 @@ public class InventoryHelper
UpdateFastPanelBinding(pmcData, matchingInventoryItem);
// Item has location property, ensure its value is handled
if (moveRequest.To.Location is not null) {
if (moveRequest.To.Location is not null)
{
matchingInventoryItem.Location = moveRequest.To.Location;
} else
}
else
{
// Moved from slot with location to one without, clean up
if (matchingInventoryItem.Location is not null)
@@ -443,7 +439,7 @@ public class InventoryHelper
protected void UpdateFastPanelBinding(PmcData pmcData, Item itemBeingMoved)
{
// Find matching _id in fast panel
if (!pmcData.Inventory.FastPanel.TryGetValue(itemBeingMoved.Id, out var fastPanelSlot))
{
return;
@@ -459,7 +455,8 @@ public class InventoryHelper
// Reset fast panel value if item was moved to a container other than pocket/rig (cant be used from fastpanel)
List<string> slots = ["pockets", "tacticalvest"];
var wasMovedToFastPanelAccessibleContainer = slots.Contains(
itemParent?.SlotId?.ToLower() ?? "");
itemParent?.SlotId?.ToLower() ?? ""
);
if (!wasMovedToFastPanelAccessibleContainer)
{
pmcData.Inventory.FastPanel[fastPanelSlot[0].ToString()] = "";
+58 -70
View File
@@ -13,22 +13,22 @@ using Core.Utils.Cloners;
namespace Core.Helpers;
[Injectable]
public class ItemHelper
public class ItemHelper(
ISptLogger<ItemHelper> _logger,
HashUtil _hashUtil,
JsonUtil _jsonUtil,
RandomUtil _randomUtil,
MathUtil _mathUtil,
DatabaseService _databaseService,
HandbookHelper _handbookHelper,
ItemBaseClassService _itemBaseClassService,
ItemFilterService _itemFilterService,
LocalisationService _localisationService,
LocaleService _localeService,
CompareUtil _compareUtil,
ICloner _cloner
)
{
protected ISptLogger<ItemHelper> _logger;
protected HashUtil _hashUtil;
protected JsonUtil _jsonUtil;
protected RandomUtil _randomUtil;
protected MathUtil _mathUtil;
protected DatabaseService _databaseService;
protected HandbookHelper _handbookHelper;
protected ItemBaseClassService _itemBaseClassService;
protected ItemFilterService _itemFilterService;
protected LocalisationService _localisationService;
protected LocaleService _localeService;
protected CompareUtil _compareUtil;
protected ICloner _cloner;
protected List<string> _defaultInvalidBaseTypes =
[
BaseClasses.LOOT_CONTAINER,
@@ -58,38 +58,6 @@ public class ItemHelper
EquipmentSlots.Scabbard.ToString()
];
public ItemHelper
(
ISptLogger<ItemHelper> logger,
HashUtil hashUtil,
JsonUtil jsonUtil,
RandomUtil randomUtil,
MathUtil mathUtil,
DatabaseService databaseService,
HandbookHelper handbookHelper,
ItemBaseClassService itemBaseClassService,
ItemFilterService itemFilterService,
LocalisationService localisationService,
LocaleService localeService,
CompareUtil compareUtil,
ICloner cloner
)
{
_logger = logger;
_hashUtil = hashUtil;
_jsonUtil = jsonUtil;
_randomUtil = randomUtil;
_mathUtil = mathUtil;
_databaseService = databaseService;
_handbookHelper = handbookHelper;
_itemBaseClassService = itemBaseClassService;
_itemFilterService = itemFilterService;
_localisationService = localisationService;
_localeService = localeService;
_compareUtil = compareUtil;
_cloner = cloner;
}
/**
* Does the provided pool of items contain the desired item
* @param itemPool Item collection to check
@@ -1836,29 +1804,34 @@ public class ItemHelper
public List<Item> ReparentItemAndChildren(Item rootItem, List<Item> itemWithChildren)
{
var oldRootId = itemWithChildren[0].Id;
Dictionary<string, string> idMappings = new ();
Dictionary<string, string> idMappings = new();
idMappings[oldRootId] = rootItem.Id;
foreach (var mod in itemWithChildren) {
if (idMappings[mod.Id] is null) {
foreach (var mod in itemWithChildren)
{
if (idMappings[mod.Id] is null)
{
idMappings[mod.Id] = _hashUtil.Generate();
}
// Has parentId + no remapping exists for its parent
if (mod.ParentId is not null && idMappings[mod.ParentId] is null) {
if (mod.ParentId is not null && idMappings[mod.ParentId] is null)
{
// Make remapping for items parentId
idMappings[mod.ParentId] = _hashUtil.Generate();
}
mod.Id = idMappings[mod.Id];
if (mod.ParentId is not null) {
if (mod.ParentId is not null)
{
mod.ParentId = idMappings[mod.ParentId];
}
}
// Force item's details into first location of presetItems
if (itemWithChildren[0].Template != rootItem.Template) {
if (itemWithChildren[0].Template != rootItem.Template)
{
_logger.Warning($"Reassigning root item from {itemWithChildren[0].Template} to {rootItem.Template}");
}
@@ -1878,19 +1851,22 @@ public class ItemHelper
{
newId = _hashUtil.Generate();
}
var rootItemExistingId = itemWithChildren[0].Id;
foreach (var item in itemWithChildren) {
foreach (var item in itemWithChildren)
{
// Root, update id
if (item.Id == rootItemExistingId) {
if (item.Id == rootItemExistingId)
{
item.Id = newId;
continue;
}
// Child with parent of root, update
if (item.ParentId == rootItemExistingId) {
if (item.ParentId == rootItemExistingId)
{
item.ParentId = newId;
}
}
@@ -1907,13 +1883,15 @@ public class ItemHelper
// Returns Array of Items that have been adopted.
public List<Item> AdoptOrphanedItems(string rootId, List<Item> items)
{
foreach (var item in items) {
foreach (var item in items)
{
// Check if the item's parent exists.
var parentExists = items.Any((parentItem) => parentItem.Id == item.ParentId);
// If the parent does not exist and the item is not already a 'hideout' item, adopt the orphaned item by
// setting the parent ID to the PMCs inventory equipment ID, the slot ID to 'hideout', and remove the location.
if (!parentExists && item.ParentId != rootId && item.SlotId != "hideout") {
if (!parentExists && item.ParentId != rootId && item.SlotId != "hideout")
{
item.ParentId = rootId;
item.SlotId = "hideout";
item.Location = null;
@@ -1929,10 +1907,12 @@ public class ItemHelper
// Returns A Map where the keys are the item IDs and the values are the corresponding Item objects.
public Dictionary<string, Item> GenerateItemsMap(List<Item> items)
{
Dictionary<string, Item> itemsMap = new ();
foreach (var item in items) {
Dictionary<string, Item> itemsMap = new();
foreach (var item in items)
{
itemsMap.Add(item.Id, item);
}
return itemsMap;
}
@@ -1942,10 +1922,12 @@ public class ItemHelper
// Returns True when upd object was added
public bool AddUpdObjectToItem(Item item, string warningMessageWhenMissing = null)
{
if (item.Upd is null) {
item.Upd = new ();
if (item.Upd is null)
{
item.Upd = new();
if (warningMessageWhenMissing is not null) {
if (warningMessageWhenMissing is not null)
{
_logger.Debug(warningMessageWhenMissing);
}
@@ -1979,19 +1961,23 @@ public class ItemHelper
public string? GetItemBaseType(string tpl, bool rootOnly = true)
{
var result = GetItem(tpl);
if (!result.Key) {
if (!result.Key)
{
// Not an item
return null;
}
var currentItem = result.Value;
while (currentItem is not null) {
if (currentItem.Type == "Node" && !rootOnly) {
while (currentItem is not null)
{
if (currentItem.Type == "Node" && !rootOnly)
{
// Hit first base type
return currentItem.Id;
}
if (currentItem.Parent is null) {
if (currentItem.Parent is null)
{
// No parent, reached root
return currentItem.Id;
}
@@ -2007,8 +1993,10 @@ public class ItemHelper
// Items to update FiR status of
public void RemoveSpawnedInSessionPropertyFromItems(List<Item> items)
{
foreach (var item in items) {
if (item.Upd is not null) {
foreach (var item in items)
{
if (item.Upd is not null)
{
item.Upd.SpawnedInSession = null;
}
}
+6 -19
View File
@@ -10,26 +10,13 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class NotificationSendHelper
public class NotificationSendHelper(
IWebSocketConnectionHandler _sptWebSocketConnectionHandler,
HashUtil _hashUtil,
SaveServer _saveServer,
NotificationService _notificationService
)
{
private readonly IWebSocketConnectionHandler _sptWebSocketConnectionHandler;
private readonly HashUtil _hashUtil;
private readonly SaveServer _saveServer;
private readonly NotificationService _notificationService;
public NotificationSendHelper(
IWebSocketConnectionHandler sptWebSocketConnectionHandler,
HashUtil hashUtil,
SaveServer saveServer,
NotificationService notificationService
)
{
_sptWebSocketConnectionHandler = sptWebSocketConnectionHandler;
_hashUtil = hashUtil;
_saveServer = saveServer;
_notificationService = notificationService;
}
/// <summary>
/// Send notification message to the appropriate channel
/// </summary>
+1 -9
View File
@@ -5,17 +5,9 @@ using Core.Models.Eft.Ws;
namespace Core.Helpers;
[Injectable(InjectionType.Singleton)]
public class NotifierHelper
public class NotifierHelper(HttpServerHelper _httpServerHelper)
{
private readonly HttpServerHelper _httpServerHelper;
protected WsPing ping = new WsPing();
public NotifierHelper(
HttpServerHelper httpServerHelper)
{
_httpServerHelper = httpServerHelper;
}
public WsNotificationEvent GetDefaultNotification() => ping;
/**
+2 -11
View File
@@ -6,18 +6,9 @@ using Core.Servers;
namespace Core.Helpers;
[Injectable]
public class PaymentHelper
public class PaymentHelper(ConfigServer _configServer)
{
protected ConfigServer _configServer;
protected InventoryConfig _inventoryConfig;
public PaymentHelper(
ConfigServer configServer)
{
_configServer = configServer;
_inventoryConfig = _configServer.GetConfig<InventoryConfig>();
}
protected InventoryConfig _inventoryConfig = _configServer.GetConfig<InventoryConfig>();
/// <summary>
/// Is the passed in tpl money (also checks custom currencies in inventoryConfig.customMoneyTpls)
+34 -32
View File
@@ -7,28 +7,16 @@ using Core.Utils.Cloners;
namespace Core.Helpers;
[Injectable(InjectionType.Singleton)]
public class PresetHelper
public class PresetHelper(
DatabaseService _databaseService,
ItemHelper _itemHelper,
ICloner _cloner
)
{
protected DatabaseService _databaseService;
protected ItemHelper _itemHelper;
protected ICloner _cloner;
protected Dictionary<string, List<string>> _lookup = new();
protected Dictionary<string, Preset> _defaultEquipmentPresets;
protected Dictionary<string, Preset> _defaultWeaponPresets;
public PresetHelper
(
DatabaseService databaseService,
ItemHelper itemHelper,
ICloner cloner
)
{
_databaseService = databaseService;
_itemHelper = itemHelper;
_cloner = cloner;
}
public void HydratePresetStore(Dictionary<string, List<string>> input)
{
_lookup = input;
@@ -55,9 +43,12 @@ public class PresetHelper
if (_defaultWeaponPresets == null)
{
var tempPresets = _databaseService.GetGlobals().ItemPresets;
tempPresets = tempPresets.Where(p =>
p.Value.Encyclopedia != null &&
_itemHelper.IsOfBaseclass(p.Value.Encyclopedia, BaseClasses.WEAPON)).ToDictionary();
tempPresets = tempPresets.Where(
p =>
p.Value.Encyclopedia != null &&
_itemHelper.IsOfBaseclass(p.Value.Encyclopedia, BaseClasses.WEAPON)
)
.ToDictionary();
}
return _defaultWeaponPresets;
@@ -72,9 +63,12 @@ public class PresetHelper
if (_defaultEquipmentPresets == null)
{
var tempPresets = _databaseService.GetGlobals().ItemPresets;
tempPresets = tempPresets.Where(p =>
p.Value.Encyclopedia != null &&
_itemHelper.ArmorItemCanHoldMods(p.Value.Encyclopedia)).ToDictionary();
tempPresets = tempPresets.Where(
p =>
p.Value.Encyclopedia != null &&
_itemHelper.ArmorItemCanHoldMods(p.Value.Encyclopedia)
)
.ToDictionary();
}
return _defaultEquipmentPresets;
@@ -98,7 +92,7 @@ public class PresetHelper
public bool HasPreset(string templateId)
{
return _lookup.ContainsKey(templateId) ;
return _lookup.ContainsKey(templateId);
}
public Preset GetPreset(string id)
@@ -113,14 +107,16 @@ public class PresetHelper
public List<Preset> GetPresets(string templateId)
{
if (!HasPreset(templateId)) {
if (!HasPreset(templateId))
{
return [];
}
List<Preset> presets = [];
var ids = _lookup[templateId];
foreach (var id in ids) {
foreach (var id in ids)
{
presets.Add(GetPreset(id));
}
@@ -134,14 +130,17 @@ public class PresetHelper
*/
public Preset? GetDefaultPreset(string templateId)
{
if (!HasPreset(templateId)) {
if (!HasPreset(templateId))
{
return null;
}
var allPresets = GetPresets(templateId);
foreach (var preset in allPresets) {
if (preset.Encyclopedia is not null) {
foreach (var preset in allPresets)
{
if (preset.Encyclopedia is not null)
{
return preset;
}
}
@@ -151,11 +150,14 @@ public class PresetHelper
public string GetBaseItemTpl(string presetId)
{
if (IsPreset(presetId)) {
if (IsPreset(presetId))
{
var preset = GetPreset(presetId);
foreach (var item in preset.Items) {
if (preset.Parent == item.Id) {
foreach (var item in preset.Items)
{
if (preset.Parent == item.Id)
{
return item.Template;
}
}
+4 -15
View File
@@ -5,22 +5,11 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class ProbabilityHelper
public class ProbabilityHelper(
ISptLogger<ProbabilityHelper> _logger,
RandomUtil _randomUtil
)
{
private readonly ISptLogger<ProbabilityHelper> _logger;
private readonly RandomUtil _randomUtil;
public ProbabilityHelper
(
ISptLogger<ProbabilityHelper> logger,
RandomUtil randomUtil
)
{
_logger = logger;
_randomUtil = randomUtil;
}
/// <summary>
/// Chance to roll a number out of 100
/// </summary>
+39 -56
View File
@@ -13,44 +13,20 @@ using Core.Utils.Cloners;
namespace Core.Helpers;
[Injectable]
public class ProfileHelper
public class ProfileHelper(
ISptLogger<ProfileHelper> _logger,
ICloner _cloner,
SaveServer _saveServer,
DatabaseService _databaseService,
Watermark _watermark,
ItemHelper _itemHelper,
TimeUtil _timeUtil,
LocalisationService _localisationService,
HashUtil _hashUtil,
ConfigServer _configServer
)
{
protected ISptLogger<ProfileHelper> _logger;
protected ICloner _cloner;
protected SaveServer _saveServer;
protected DatabaseService _databaseService;
protected Watermark _watermark;
protected ItemHelper _itemHelper;
protected TimeUtil _timeUtil;
protected LocalisationService _localisationService;
protected InventoryConfig _inventoryConfig;
protected HashUtil _hashUtil;
public ProfileHelper(
ISptLogger<ProfileHelper> logger,
ICloner cloner,
SaveServer saveServer,
DatabaseService databaseService,
Watermark watermark,
ItemHelper itemHelper,
TimeUtil timeUtil,
LocalisationService localisationService,
HashUtil hashUtil,
ConfigServer configServer
)
{
_logger = logger;
_cloner = cloner;
_saveServer = saveServer;
_databaseService = databaseService;
_watermark = watermark;
_itemHelper = itemHelper;
_timeUtil = timeUtil;
_localisationService = localisationService;
_hashUtil = hashUtil;
_inventoryConfig = configServer.GetConfig<InventoryConfig>();
}
protected InventoryConfig _inventoryConfig = _configServer.GetConfig<InventoryConfig>();
/// <summary>
/// Remove/reset a completed quest condtion from players profile quest data
@@ -127,9 +103,12 @@ public class ProfileHelper
var allProfiles = _saveServer.GetProfiles().Values;
// Find a profile that doesn't have same session id but has same name
return allProfiles.Any(p =>
ProfileHasInfoProperty(p) && !StringsMatch(p.ProfileInfo.ProfileId, sessionID) && // SessionIds dont match
StringsMatch(p.CharacterData.PmcData.Info.LowerNickname.ToLower(), nicknameRequest.Nickname.ToLower())); // Nicknames do
return allProfiles.Any(
p =>
ProfileHasInfoProperty(p) &&
!StringsMatch(p.ProfileInfo.ProfileId, sessionID) && // SessionIds dont match
StringsMatch(p.CharacterData.PmcData.Info.LowerNickname.ToLower(), nicknameRequest.Nickname.ToLower())
); // Nicknames do
}
protected bool ProfileHasInfoProperty(SptProfile profile)
@@ -389,12 +368,14 @@ public class ProfileHelper
}
// Player has never received gift, make a new object
profileToUpdate.SptData.ReceivedGifts.Add(new()
{
GiftId = giftId,
TimestampLastAccepted = _timeUtil.GetTimeStamp(),
Current = 1
});
profileToUpdate.SptData.ReceivedGifts.Add(
new()
{
GiftId = giftId,
TimestampLastAccepted = _timeUtil.GetTimeStamp(),
Current = 1
}
);
}
/// <summary>
@@ -539,15 +520,17 @@ public class ProfileHelper
var existingBonus = profile?.Bonuses?.FirstOrDefault(b => b.Type == BonusType.StashRows);
if (existingBonus != null)
{
profile?.Bonuses?.Add(new()
{
Id = _hashUtil.Generate(),
Value = rowsToAdd,
Type = BonusType.StashRows,
IsPassive = true,
IsVisible = true,
IsProduction = false
});
profile?.Bonuses?.Add(
new()
{
Id = _hashUtil.Generate(),
Value = rowsToAdd,
Type = BonusType.StashRows,
IsPassive = true,
IsVisible = true,
IsProduction = false
}
);
}
else
{
@@ -706,7 +689,7 @@ public class ProfileHelper
_logger.Error($"Unhandled customisation unlock type: {matchingCustomisation.Parent} not added to profile");
return;
}
fullProfile.CustomisationUnlocks.Add(rewardToStore);
}
}
+46 -78
View File
@@ -16,69 +16,27 @@ using Product = Core.Models.Eft.ItemEvent.Product;
namespace Core.Helpers;
[Injectable]
public class QuestHelper
public class QuestHelper(
ISptLogger<QuestHelper> _logger,
TimeUtil _timeUtil,
HashUtil _hashUtil,
ItemHelper _itemHelper,
DatabaseService _databaseService,
QuestConditionHelper _questConditionHelper,
EventOutputHolder _eventOutputHolder,
LocaleService _localeService,
ProfileHelper _profileHelper,
QuestRewardHelper _questRewardHelper,
LocalisationService _localisationService,
SeasonalEventService _seasonalEventService,
TraderHelper _traderHelper,
MailSendService _mailSendService,
PlayerService _playerService,
ConfigServer _configServer,
ICloner _cloner
)
{
protected ISptLogger<QuestHelper> _logger;
protected TimeUtil _timeUtil;
protected HashUtil _hashUtil;
protected ItemHelper _itemHelper;
protected DatabaseService _databaseService;
protected QuestConditionHelper _questConditionHelper;
protected EventOutputHolder _eventOutputHolder;
protected LocaleService _localeService;
protected ProfileHelper _profileHelper;
protected QuestRewardHelper _questRewardHelper;
protected LocalisationService _localisationService;
protected SeasonalEventService _seasonalEventService;
protected TraderHelper _traderHelper;
protected MailSendService _mailSendService;
protected PlayerService _playerService;
protected ConfigServer _configServer;
protected ICloner _cloner;
protected QuestConfig _questConfig;
public QuestHelper
(
ISptLogger<QuestHelper> logger,
TimeUtil timeUtil,
HashUtil hashUtil,
ItemHelper itemHelper,
DatabaseService databaseService,
QuestConditionHelper questConditionHelper,
EventOutputHolder eventOutputHolder,
LocaleService localeService,
ProfileHelper profileHelper,
QuestRewardHelper questRewardHelper,
LocalisationService localisationService,
SeasonalEventService seasonalEventService,
TraderHelper traderHelper,
MailSendService mailSendService,
PlayerService playerService,
ConfigServer configServer,
ICloner Cloner
)
{
_logger = logger;
_timeUtil = timeUtil;
_hashUtil = hashUtil;
_itemHelper = itemHelper;
_databaseService = databaseService;
_questConditionHelper = questConditionHelper;
_eventOutputHolder = eventOutputHolder;
_localeService = localeService;
_profileHelper = profileHelper;
_questRewardHelper = questRewardHelper;
_localisationService = localisationService;
_seasonalEventService = seasonalEventService;
_traderHelper = traderHelper;
_mailSendService = mailSendService;
_playerService = playerService;
_configServer = configServer;
_cloner = Cloner;
_questConfig = configServer.GetConfig<QuestConfig>();
}
protected QuestConfig _questConfig = _configServer.GetConfig<QuestConfig>();
/// <summary>
/// Get status of a quest in player profile by its id
@@ -359,9 +317,8 @@ public class QuestHelper
var acceptedQuestCondition = q.Conditions.AvailableForStart.FirstOrDefault(
(c) =>
{
return (c.ConditionType == "Quest"
&& ((List<string>)c.Target).Contains(failedQuestId) && c.Status[0] == QuestStatusEnum.Fail
);
return (c.ConditionType == "Quest" && ((List<string>)c.Target).Contains(failedQuestId) && c.Status[0] == QuestStatusEnum.Fail
);
}
);
@@ -761,14 +718,19 @@ public class QuestHelper
public List<Quest> GetQuestsFailedByCompletingQuest(string completedQuestId)
{
var questsInDb = GetQuestsFromDb();
return questsInDb.Where((quest) => {
// No fail conditions, exit early
if (quest.Conditions.Fail is null || quest.Conditions.Fail.Count == 0) {
return false;
}
return questsInDb.Where(
(quest) =>
{
// No fail conditions, exit early
if (quest.Conditions.Fail is null || quest.Conditions.Fail.Count == 0)
{
return false;
}
return quest.Conditions.Fail.Any((condition) => (((List<string>)condition.Target)?.Contains(completedQuestId)) ?? false);
}).ToList();
return quest.Conditions.Fail.Any((condition) => (((List<string>)condition.Target)?.Contains(completedQuestId)) ?? false);
}
)
.ToList();
}
/**
@@ -779,7 +741,8 @@ public class QuestHelper
public double? GetMailItemRedeemTimeHoursForProfile(PmcData pmcData)
{
var value = _questConfig.MailRedeemTimeHours.GetValueOrDefault(pmcData.Info.GameVersion);
if (value is null) {
if (value is null)
{
return 0;
}
@@ -808,7 +771,8 @@ public class QuestHelper
// Check for linked failed + unrestartable quests (only get quests not already failed
var questsToFail = GetQuestsFromProfileFailedByCompletingQuest(completedQuestId, pmcData);
if (questsToFail?.Count > 0) {
if (questsToFail?.Count > 0)
{
FailQuests(sessionID, pmcData, questsToFail, completeQuestResponse);
}
@@ -825,13 +789,16 @@ public class QuestHelper
completeQuestResponse.ProfileChanges[sessionID].Quests.AddRange(questDelta);
// Check if it's a repeatable quest. If so, remove from Quests
foreach (var currentRepeatable in pmcData.RepeatableQuests) {
foreach (var currentRepeatable in pmcData.RepeatableQuests)
{
var repeatableQuest = currentRepeatable.ActiveQuests.FirstOrDefault(
(activeRepeatable) => activeRepeatable.Id == completedQuestId
);
if (repeatableQuest is not null) {
if (repeatableQuest is not null)
{
// Need to remove redundant scav quest object as its no longer necessary, is tracked in pmc profile
if (repeatableQuest.Side == "Scav") {
if (repeatableQuest.Side == "Scav")
{
RemoveQuestFromScavProfile(sessionID, repeatableQuest.Id);
}
}
@@ -839,7 +806,8 @@ public class QuestHelper
// Hydrate client response questsStatus array with data
var questStatusChanges = GetQuestsWithDifferentStatuses(preCompleteProfileQuests, pmcData.Quests);
if (questStatusChanges is not null) {
if (questStatusChanges is not null)
{
completeQuestResponse.ProfileChanges[sessionID].QuestsStatus.AddRange(questStatusChanges);
}
+86 -86
View File
@@ -15,53 +15,23 @@ using Core.Utils.Cloners;
namespace Core.Helpers;
[Injectable]
public class QuestRewardHelper
public class QuestRewardHelper(
ISptLogger<QuestRewardHelper> _logger,
HashUtil _hashUtil,
TimeUtil _timeUtil,
ItemHelper _itemHelper,
PaymentHelper _paymentHelper,
TraderHelper _traderHelper,
DatabaseService _databaseService,
QuestConditionHelper _questConditionHelper,
ProfileHelper _profileHelper,
PresetHelper _presetHelper,
LocalisationService _localisationService,
ICloner _cloner,
ConfigServer _configServer
)
{
protected ISptLogger<QuestRewardHelper> _logger;
protected HashUtil _hashUtil;
protected TimeUtil _timeUtil;
protected ItemHelper _itemHelper;
protected PaymentHelper _paymentHelper;
protected TraderHelper _traderHelper;
protected DatabaseService _databaseService;
protected QuestConditionHelper _questConditionHelper;
protected ProfileHelper _profileHelper;
protected PresetHelper _presetHelper;
protected LocalisationService _localisationService;
protected QuestConfig _questConfig;
protected ICloner _cloner;
public QuestRewardHelper(
ISptLogger<QuestRewardHelper> logger,
HashUtil hashUtil,
TimeUtil timeUtil,
ItemHelper itemHelper,
PaymentHelper paymentHelper,
TraderHelper traderHelper,
DatabaseService databaseService,
QuestConditionHelper questConditionHelper,
ProfileHelper profileHelper,
PresetHelper presetHelper,
LocalisationService localisationService,
ConfigServer configServer,
ICloner cloner
)
{
_logger = logger;
_hashUtil = hashUtil;
_timeUtil = timeUtil;
_itemHelper = itemHelper;
_paymentHelper = paymentHelper;
_traderHelper = traderHelper;
_databaseService = databaseService;
_questConditionHelper = questConditionHelper;
_profileHelper = profileHelper;
_presetHelper = presetHelper;
_localisationService = localisationService;
_cloner = cloner;
_questConfig = configServer.GetConfig<QuestConfig>();
}
protected QuestConfig _questConfig = _configServer.GetConfig<QuestConfig>();
/**
* Give player quest rewards - Skills/exp/trader standing/items/assort unlocks - Returns reward items player earned
@@ -99,8 +69,13 @@ public class QuestRewardHelper
// e.g. 'Success' or 'AvailableForFinish'
var questStateAsString = state.ToString();
var gameVersion = pmcProfile.Info.GameVersion;
var questRewards = (List<Reward>?)questDetails.Rewards.GetType().GetProperties().FirstOrDefault(p =>
p.Name == questStateAsString).GetValue(questDetails.Rewards);
var questRewards = (List<Reward>?)questDetails.Rewards.GetType()
.GetProperties()
.FirstOrDefault(
p =>
p.Name == questStateAsString
)
.GetValue(questDetails.Rewards);
foreach (var reward in questRewards)
{
if (!QuestRewardIsForGameEdition(reward, gameVersion))
@@ -150,12 +125,17 @@ public class QuestRewardHelper
_profileHelper.AddHideoutCustomisationUnlock(fullProfile, reward, CustomisationSource.UNLOCKED_IN_GAME);
break;
default:
_logger.Error(_localisationService.GetText("quest-reward_type_not_handled", new
{
rewardType = reward.Type,
questId = questId,
questName = questDetails.QuestName
}));
_logger.Error(
_localisationService.GetText(
"quest-reward_type_not_handled",
new
{
rewardType = reward.Type,
questId = questId,
questName = questDetails.QuestName
}
)
);
break;
}
}
@@ -246,11 +226,16 @@ public class QuestRewardHelper
*/
public Quest ApplyMoneyBoost(Quest quest, double bonusPercent, QuestStatusEnum questStatus)
{
var rewards = (List<Reward>)quest?.Rewards.GetType().GetProperties().FirstOrDefault(p => p.Name == questStatus.ToString())
.GetValue(quest.Rewards) ?? new();
var currencyRewards = rewards.Where(r =>
r.Type.ToString() == "Item" &&
_paymentHelper.IsMoneyTpl(r.Items[0].Template));
var rewards = (List<Reward>)quest?.Rewards.GetType()
.GetProperties()
.FirstOrDefault(p => p.Name == questStatus.ToString())
.GetValue(quest.Rewards) ??
new();
var currencyRewards = rewards.Where(
r =>
r.Type.ToString() == "Item" &&
_paymentHelper.IsMoneyTpl(r.Items[0].Template)
);
foreach (var reward in currencyRewards)
{
// Add % bonus to existing StackObjectsCount
@@ -278,11 +263,16 @@ public class QuestRewardHelper
var matchingProductions = GetRewardProductionMatch(craftUnlockReward, questDetails);
if (matchingProductions.Count != 1)
{
_logger.Error(_localisationService.GetText("quest-unable_to_find_matching_hideout_production", new
{
questName = questDetails.QuestName,
matchCount = matchingProductions.Count
}));
_logger.Error(
_localisationService.GetText(
"quest-unable_to_find_matching_hideout_production",
new
{
questName = questDetails.QuestName,
matchCount = matchingProductions.Count
}
)
);
return;
}
@@ -307,17 +297,23 @@ public class QuestRewardHelper
// Area that will be used to craft unlocked item
var desiredHideoutAreaType = int.Parse((string)craftUnlockReward.TraderId);
var matchingProductions = craftingRecipes.Where(p =>
p.AreaType == desiredHideoutAreaType &&
p.Requirements.Any(r => r.Type == "QuestComplete") &&
p.Requirements.Any(r => r.RequiredLevel == craftUnlockReward.LoyaltyLevel) &&
p.EndProduct == craftUnlockReward.Items[0].Template);
var matchingProductions = craftingRecipes.Where(
p =>
p.AreaType == desiredHideoutAreaType &&
p.Requirements.Any(r => r.Type == "QuestComplete") &&
p.Requirements.Any(r => r.RequiredLevel == craftUnlockReward.LoyaltyLevel) &&
p.EndProduct == craftUnlockReward.Items[0].Template
);
// More/less than single match, above filtering wasn't strict enough
if (matchingProductions.Count() != 1)
matchingProductions = matchingProductions.Where(p =>
p.Requirements.Any(r =>
r.QuestId == questDetails.Id));
matchingProductions = matchingProductions.Where(
p =>
p.Requirements.Any(
r =>
r.QuestId == questDetails.Id
)
);
return matchingProductions.ToList();
}
@@ -330,18 +326,22 @@ public class QuestRewardHelper
*/
protected List<Item> GetQuestRewardItems(Quest quest, QuestStatusEnum status, string gameVersion)
{
var rewards = (List<Reward>)quest?.Rewards.GetType().GetProperties().FirstOrDefault(p => p.Name == status.ToString())
var rewards = (List<Reward>)quest?.Rewards.GetType()
.GetProperties()
.FirstOrDefault(p => p.Name == status.ToString())
.GetValue(quest.Rewards);
if (rewards == null)
return new();
// Iterate over all rewards with the desired status, flatten out items that have a type of Item
var questRewards = rewards.SelectMany(r =>
r.Type.ToString() == "Item" &&
QuestRewardIsForGameEdition(r, gameVersion)
? ProcessReward(r)
: new());
var questRewards = rewards.SelectMany(
r =>
r.Type.ToString() == "Item" &&
QuestRewardIsForGameEdition(r, gameVersion)
? ProcessReward(r)
: new()
);
return questRewards.ToList();
}
@@ -416,10 +416,10 @@ public class QuestRewardHelper
{
itemsClone.Add(_cloner.Clone(mod));
}
rewardItems.AddRange(_itemHelper.ReparentItemAndChildren(target, itemsClone));
}
return rewardItems;
}
@@ -439,24 +439,24 @@ public class QuestRewardHelper
var newRootId = _itemHelper.RemapRootItemId(presetAndMods, _hashUtil.Generate());
reward.Items = presetAndMods;
// Find root item and set its stack count
var rootItem = reward.Items.FirstOrDefault(i => i.Id == newRootId);
// Remap target id to the new presets root id
reward.Target = rootItem.Id;
// Copy over stack count otherwise reward shows as missing in client
_itemHelper.AddUpdObjectToItem(rootItem);
rootItem.Upd.StackObjectsCount = originalRewardRootItem.Upd.StackObjectsCount;
return;
}
_logger.Warning($"Unable to find default preset for armor {originalRewardRootItem.Template}, adding mods manually");
var itemDbData = _itemHelper.GetItem(originalRewardRootItem.Template).Value;
// Hydrate reward with only 'required' mods - necessary for things like helmets otherwise you end up with nvgs/visors etc
reward.Items = _itemHelper.AddChildSlotItems(reward.Items, itemDbData, null, true);
}
+5 -16
View File
@@ -8,23 +8,12 @@ using Core.Utils.Collections;
namespace Core.Helpers;
[Injectable]
public class RepeatableQuestHelper
public class RepeatableQuestHelper(
ISptLogger<RepeatableQuestHelper> _logger,
ICloner _cloner,
MathUtil _mathUtil
)
{
protected ISptLogger<RepeatableQuestHelper> _logger;
protected ICloner _cloner;
protected MathUtil _mathUtil;
public RepeatableQuestHelper(
ISptLogger<RepeatableQuestHelper> logger,
ICloner cloner,
MathUtil mathUtil
)
{
_logger = logger;
_cloner = cloner;
_mathUtil = mathUtil;
}
/// <summary>
/// Get the relevant elimination config based on the current players PMC level
/// </summary>
+1 -5
View File
@@ -7,12 +7,8 @@ using Core.Models.Eft.Trade;
namespace Core.Helpers;
[Injectable]
public class TradeHelper
public class TradeHelper()
{
public TradeHelper()
{
}
/// <summary>
/// Buy item from flea or trader
+1 -5
View File
@@ -4,12 +4,8 @@ using Core.Models.Eft.Common.Tables;
namespace Core.Helpers;
[Injectable]
public class TraderAssortHelper
public class TraderAssortHelper()
{
public TraderAssortHelper()
{
}
/// <summary>
/// Get a traders assorts
+30 -44
View File
@@ -14,40 +14,19 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class TraderHelper
public class TraderHelper(
ISptLogger<TraderHelper> _logger,
TimeUtil _timeUtil,
RandomUtil _randomUtil,
LocalisationService _localisationService,
ConfigServer _configServer,
ProfileHelper _profileHelper,
DatabaseService _databaseService
)
{
protected ISptLogger<TraderHelper> _logger;
protected TimeUtil _timeUtil;
protected RandomUtil _randomUtil;
protected LocalisationService _localisationService;
protected ConfigServer _configServer;
protected TraderConfig _traderConfig;
protected ProfileHelper _profileHelper;
protected DatabaseService _databaseService;
protected TraderConfig _traderConfig = _configServer.GetConfig<TraderConfig>();
private Dictionary<string, int> _highestTraderPriceItems = new();
public TraderHelper(
ISptLogger<TraderHelper> logger,
TimeUtil timeUtil,
RandomUtil randomUtil,
LocalisationService localisationService,
ConfigServer configServer,
ProfileHelper profileHelper,
DatabaseService databaseService
)
{
_logger = logger;
_timeUtil = timeUtil;
_randomUtil = randomUtil;
_localisationService = localisationService;
_configServer = configServer;
_profileHelper = profileHelper;
_databaseService = databaseService;
_traderConfig = _configServer.GetConfig<TraderConfig>();
}
/// <summary>
/// Get a trader base object, update profile to reflect players current standing in profile
/// when trader not found in profile
@@ -68,7 +47,7 @@ public class TraderHelper
var pmcData = _profileHelper.GetPmcProfile(sessionID);
if (pmcData == null)
throw new Exception(_localisationService.GetText("trader-unable_to_find_profile_with_id", sessionID));
// Profile has traderInfo dict (profile beyond creation stage) but no requested trader in profile
if (pmcData?.TradersInfo != null && (pmcData?.TradersInfo?.ContainsKey(traderID) ?? false))
{
@@ -80,7 +59,7 @@ public class TraderHelper
var traderBase = _databaseService.GetTrader(traderID).Base;
if (traderBase == null)
_logger.Error(_localisationService.GetText("trader-unable_to_find_trader_by_id", traderID));
return traderBase;
}
@@ -214,18 +193,25 @@ public class TraderHelper
var traderDetails = _traderConfig.UpdateTime.FirstOrDefault((x) => x.TraderId == traderId);
if (traderDetails is null || traderDetails.Seconds?.Min is null || traderDetails.Seconds.Max is null)
{
_logger.Warning(_localisationService.GetText("trader-missing_trader_details_using_default_refresh_time", new
{
traderId = traderId,
updateTime = _traderConfig.UpdateTimeDefault,
}));
_logger.Warning(
_localisationService.GetText(
"trader-missing_trader_details_using_default_refresh_time",
new
{
traderId = traderId,
updateTime = _traderConfig.UpdateTimeDefault,
}
)
);
_traderConfig.UpdateTime.Add(new UpdateTime
// create temporary entry to prevent logger spam
{
TraderId = traderId,
Seconds = new MinMax { Min = _traderConfig.UpdateTimeDefault, Max = _traderConfig.UpdateTimeDefault }
});
_traderConfig.UpdateTime.Add(
new UpdateTime
// create temporary entry to prevent logger spam
{
TraderId = traderId,
Seconds = new MinMax { Min = _traderConfig.UpdateTimeDefault, Max = _traderConfig.UpdateTimeDefault }
}
);
return null;
}
+12 -24
View File
@@ -9,27 +9,13 @@ using Core.Utils;
namespace Core.Helpers;
[Injectable]
public class WeatherHelper
public class WeatherHelper(
ISptLogger<WeatherHelper> _logger,
TimeUtil _timeUtil,
ConfigServer _configServer
)
{
protected ISptLogger<WeatherHelper> _logger;
protected TimeUtil _timeUtil;
protected ConfigServer _configServer;
protected WeatherConfig _weatherConfig;
public WeatherHelper
(
ISptLogger<WeatherHelper> logger,
TimeUtil timeUtil,
ConfigServer configServer
)
{
_logger = logger;
_timeUtil = timeUtil;
_configServer = configServer;
_weatherConfig = _configServer.GetConfig<WeatherConfig>();
}
protected WeatherConfig _weatherConfig = _configServer.GetConfig<WeatherConfig>();
/// <summary>
/// Get the current in-raid time - does not include an accurate date, only time
@@ -45,9 +31,11 @@ public class WeatherHelper
? timestamp ?? 0
: _timeUtil.GetTimeStampFromEpoch();
return _timeUtil.GetDateTimeFromTimeStamp((long)
return _timeUtil.GetDateTimeFromTimeStamp(
(long)
(russiaOffsetMilliseconds + currentTimestampMilliSeconds * _weatherConfig.Acceleration) %
twentyFourHoursMilliseconds);
twentyFourHoursMilliseconds
);
}
/// <summary>
@@ -58,11 +46,11 @@ public class WeatherHelper
public bool IsNightTime(DateTimeEnum timeVariant)
{
var time = GetInRaidTime();
// getInRaidTime() provides left side value, if player chose right side, set ahead 12 hrs
if (timeVariant == DateTimeEnum.PAST)
time.AddHours(12);
// Night if after 9pm or before 5am
return time.Hour > 21 || time.Hour < 5;
}
+3 -10
View File
@@ -6,17 +6,10 @@ using Core.Models.Utils;
namespace Core.Helpers;
[Injectable]
public class WeightedRandomHelper
public class WeightedRandomHelper(
ISptLogger<WeightedRandomHelper> _logger
)
{
protected ISptLogger<WeightedRandomHelper> _logger;
public WeightedRandomHelper(
ISptLogger<WeightedRandomHelper> logger
)
{
_logger = logger;
}
/// <summary>
/// Choose an item from the passed in array based on the weightings of each
/// </summary>