formatting, fix build error

This commit is contained in:
CWX
2025-02-05 07:36:13 +00:00
parent f648f42721
commit a4f8036d09
88 changed files with 514 additions and 502 deletions
+5 -5
View File
@@ -8,14 +8,14 @@ namespace ExampleMods.Mods;
[Injectable]
public class EditConfigs
{
private readonly AirdropConfig _airdropConfig;
private readonly BotConfig _botConfig;
private readonly ConfigServer _configServer;
private readonly BotConfig _botConfig;
private readonly HideoutConfig _hideoutConfig;
private readonly PmcChatResponse _pmcChatResponseConfig;
private readonly PmcConfig _pmcConfig;
private readonly QuestConfig _questConfig;
private readonly WeatherConfig _weatherConfig;
private readonly AirdropConfig _airdropConfig;
private readonly PmcChatResponse _pmcChatResponseConfig;
private readonly QuestConfig _questConfig;
private readonly PmcConfig _pmcConfig;
// We access configs via ConfigServer
public EditConfigs(
+11 -11
View File
@@ -18,17 +18,6 @@ public class DialogueCallbacks(
)
: OnUpdate
{
public bool OnUpdate(long timeSinceLastRun)
{
_dialogueController.Update();
return true;
}
public string GetRoute()
{
return "spt-dialogue";
}
/// <summary>
/// Handle client/friend/list
/// </summary>
@@ -326,4 +315,15 @@ public class DialogueCallbacks(
{
return "Not Implemented!"; // Not implemented in Node
}
public bool OnUpdate(long timeSinceLastRun)
{
_dialogueController.Update();
return true;
}
public string GetRoute()
{
return "spt-dialogue";
}
}
+16 -16
View File
@@ -18,22 +18,6 @@ public class HideoutCallbacks(
{
private readonly HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
public bool OnUpdate(long timeSinceLastRun)
{
if (timeSinceLastRun > _hideoutConfig.RunIntervalSeconds)
{
_hideoutController.Update();
return true;
}
return false;
}
public string GetRoute()
{
return "spt-hideout";
}
/// <summary>
/// Handle HideoutUpgrade event
/// </summary>
@@ -178,4 +162,20 @@ public class HideoutCallbacks(
{
return _hideoutController.HideoutCustomizationSetMannequinPose(sessionId, pmcData, request);
}
public bool OnUpdate(long timeSinceLastRun)
{
if (timeSinceLastRun > _hideoutConfig.RunIntervalSeconds)
{
_hideoutController.Update();
return true;
}
return false;
}
public string GetRoute()
{
return "spt-hideout";
}
}
+15 -15
View File
@@ -23,21 +23,6 @@ public class InsuranceCallbacks(
{
private InsuranceConfig _insuranceConfig = _configServer.GetConfig<InsuranceConfig>();
public bool OnUpdate(long timeSinceLastRun)
{
if (timeSinceLastRun > Math.Max(_insuranceConfig.RunIntervalSeconds, 1))
// _insuranceController.ProcessReturn();
// TODO: InsuranceController is not implemented rn
return true;
return false;
}
public string GetRoute()
{
return "spt-insurance";
}
/// <summary>
/// Handle client/insurance/items/list/cost
/// </summary>
@@ -61,4 +46,19 @@ public class InsuranceCallbacks(
{
return _insuranceController.Insure(pmcData, info, sessionID);
}
public bool OnUpdate(long timeSinceLastRun)
{
if (timeSinceLastRun > Math.Max(_insuranceConfig.RunIntervalSeconds, 1))
// _insuranceController.ProcessReturn();
// TODO: InsuranceController is not implemented rn
return true;
return false;
}
public string GetRoute()
{
return "spt-insurance";
}
}
+5 -5
View File
@@ -23,11 +23,6 @@ public class SaveCallbacks(
_saveServer.Load();
}
public string GetRoute()
{
return "spt-save";
}
public bool OnUpdate(long secondsSinceLastRun)
{
if (secondsSinceLastRun > _coreConfig.ProfileSaveIntervalInSeconds)
@@ -38,4 +33,9 @@ public class SaveCallbacks(
return false;
}
public string GetRoute()
{
return "spt-save";
}
}
+5 -5
View File
@@ -25,16 +25,16 @@ public class TraderCallbacks(
return Task.CompletedTask;
}
public string GetRoute()
{
return "spt-traders";
}
public bool OnUpdate(long _)
{
return _traderController.Update();
}
public string GetRoute()
{
return "spt-traders";
}
/// <summary>
/// Handle client/trading/api/traderSettings
/// </summary>
+3 -3
View File
@@ -44,12 +44,12 @@ public class GameController(
ICloner _cloner
)
{
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
protected double _deviation = 0.0001;
protected HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
protected HttpConfig _httpConfig = _configServer.GetConfig<HttpConfig>();
protected RagfairConfig _ragfairConfig = _configServer.GetConfig<RagfairConfig>();
protected HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected double _deviation = 0.0001;
/// <summary>
/// Handle client/game/start
@@ -46,6 +46,7 @@ public class HideoutController(
ConfigServer _configServer
)
{
protected HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
public const string NameTaskConditionCountersCraftingId = "673f5d6fdd6ed700c703afdc";
protected List<HideoutAreas> _hideoutAreas =
@@ -56,8 +57,6 @@ public class HideoutController(
HideoutAreas.BITCOIN_FARM
];
protected HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
public void StartUpgrade(PmcData pmcData, HideoutUpgradeRequestData request, string sessionID, ItemEventRouterResponse output)
{
var items = request.Items.Select(
@@ -16,8 +16,8 @@ public class InRaidController(
ConfigServer _configServer
)
{
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected InRaidConfig _inRaidConfig = _configServer.GetConfig<InRaidConfig>();
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
/// <summary>
/// Save locationId to active profiles in-raid object AND app context
@@ -71,9 +71,19 @@ public class PrestigeController(
// hideout progress
// going to prestige 2
// most likely the same, but wait for dump of new beginnings quest
// 10% of skills should be transfered over
// 10% of mastering should be transfered over
// earned achievements should be transfered over
// profile stats should be transfered over
// prestige progress should be transfered over
// reset
// trader standing
// task progress
// character level
// stash
// hideout progress
// Clone existing profile, create a new one
var prePrestigeProfileClone = _cloner.Clone(_profileHelper.GetFullProfile(sessionId));
var prePrestigePmc = prePrestigeProfileClone.CharacterData.PmcData;
+28 -28
View File
@@ -25,32 +25,32 @@ namespace Core.Controllers;
[Injectable]
public class RagfairController
{
private readonly ConfigServer _configServer;
private readonly DatabaseService _databaseService;
private readonly EventOutputHolder _eventOutputHolder;
private readonly HandbookHelper _handbookHelper;
private readonly HttpResponseUtil _httpResponseUtil;
private readonly InventoryHelper _inventoryHelper;
private readonly ItemHelper _itemHelper;
private readonly JsonUtil _jsonUtil;
private readonly LocalisationService _localisationService;
private readonly ISptLogger<RagfairController> _logger;
private readonly PaymentHelper _paymentHelper;
private readonly PaymentService _paymentService;
private readonly TimeUtil _timeUtil;
private readonly JsonUtil _jsonUtil;
private readonly HttpResponseUtil _httpResponseUtil;
private readonly EventOutputHolder _eventOutputHolder;
private readonly RagfairServer _ragfairServer;
private readonly ItemHelper _itemHelper;
private readonly InventoryHelper _inventoryHelper;
private readonly RagfairSellHelper _ragfairSellHelper;
private readonly HandbookHelper _handbookHelper;
private readonly ProfileHelper _profileHelper;
private readonly PaymentHelper _paymentHelper;
private readonly RagfairHelper _ragfairHelper;
private readonly RagfairSortHelper _ragfairSortHelper;
private readonly RagfairOfferHelper _ragfairOfferHelper;
private readonly TraderHelper _traderHelper;
private readonly DatabaseService _databaseService;
private readonly LocalisationService _localisationService;
private readonly RagfairTaxService _ragfairTaxService;
private readonly RagfairOfferService _ragfairOfferService;
private readonly PaymentService _paymentService;
private readonly RagfairPriceService _ragfairPriceService;
private readonly RagfairOfferGenerator _ragfairOfferGenerator;
private readonly ConfigServer _configServer;
private readonly RagfairConfig _ragfairConfig;
private readonly RagfairHelper _ragfairHelper;
private readonly RagfairOfferGenerator _ragfairOfferGenerator;
private readonly RagfairOfferHelper _ragfairOfferHelper;
private readonly RagfairOfferService _ragfairOfferService;
private readonly RagfairPriceService _ragfairPriceService;
private readonly RagfairSellHelper _ragfairSellHelper;
private readonly RagfairServer _ragfairServer;
private readonly RagfairSortHelper _ragfairSortHelper;
private readonly RagfairTaxService _ragfairTaxService;
private readonly TimeUtil _timeUtil;
private readonly TraderHelper _traderHelper;
public RagfairController(
ISptLogger<RagfairController> logger,
@@ -879,6 +879,12 @@ public class RagfairController
return new GetItemsToListOnFleaFromInventoryResult { Items = itemsToReturn, ErrorMessage = errorMessage };
}
public record GetItemsToListOnFleaFromInventoryResult
{
public List<List<Item>>? Items { get; set; }
public string? ErrorMessage { get; set; }
}
public ItemEventRouterResponse RemoveOffer(RemoveOfferRequestData removeRequest, string sessionId)
{
var output = _eventOutputHolder.GetOutput(sessionId);
@@ -1022,10 +1028,4 @@ public class RagfairController
return offerToReturn;
}
public record GetItemsToListOnFleaFromInventoryResult
{
public List<List<Item>>? Items { get; set; }
public string? ErrorMessage { get; set; }
}
}
+1 -1
View File
@@ -66,8 +66,8 @@ public abstract class StaticRouter : Router
public abstract class DynamicRouter : Router
{
private readonly JsonUtil _jsonUtil;
private readonly List<RouteAction> actions;
private readonly JsonUtil _jsonUtil;
public DynamicRouter(JsonUtil jsonUtil, List<RouteAction> routes) : base()
{
@@ -34,11 +34,11 @@ public class BotWeaponGenerator(
IEnumerable<IInventoryMagGen> inventoryMagGenComponents
)
{
protected const string _modMagazineSlotId = "mod_magazine";
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected IEnumerable<IInventoryMagGen> _inventoryMagGenComponents = MagGenSetUp(inventoryMagGenComponents);
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected PmcConfig _pmcConfig = _configServer.GetConfig<PmcConfig>();
protected RepairConfig _repairConfig = _configServer.GetConfig<RepairConfig>();
protected const string _modMagazineSlotId = "mod_magazine";
private static List<IInventoryMagGen> MagGenSetUp(IEnumerable<IInventoryMagGen> components)
{
+6 -6
View File
@@ -241,6 +241,12 @@ public class LootGenerator(
return new ItemRewardPoolResults { ItemPool = items, Blacklist = itemBlacklist };
}
public record ItemRewardPoolResults
{
public List<TemplateItem> ItemPool { get; set; }
public HashSet<string> Blacklist { get; set; }
}
/// <summary>
/// Filter armor items by their front plates protection level - top if it's a helmet
/// </summary>
@@ -648,12 +654,6 @@ public class LootGenerator(
)
);
}
public record ItemRewardPoolResults
{
public List<TemplateItem> ItemPool { get; set; }
public HashSet<string> Blacklist { get; set; }
}
}
public class ItemLimit
@@ -12,19 +12,19 @@ namespace Core.Generators;
[Injectable]
public class PMCLootGenerator
{
private readonly ConfigServer _configServer;
private readonly DatabaseService _databaseService;
private readonly ItemFilterService _itemFilterService;
private readonly ItemHelper _itemHelper;
private readonly ISptLogger<PMCLootGenerator> _logger;
private readonly PmcConfig _pmcConfig;
private readonly DatabaseService _databaseService;
private readonly ItemHelper _itemHelper;
private readonly ItemFilterService _itemFilterService;
private readonly RagfairPriceService _ragfairPriceService;
private readonly SeasonalEventService _seasonalEventService;
private readonly WeightedRandomHelper _weightedRandomHelper;
private readonly ConfigServer _configServer;
private Dictionary<string, double>? _backpackLootPool;
private Dictionary<string, double>? _pocketLootPool;
private Dictionary<string, double>? _vestLootPool;
private readonly PmcConfig _pmcConfig;
public PMCLootGenerator(
ISptLogger<PMCLootGenerator> logger,
@@ -43,15 +43,14 @@ public class RagfairOfferGenerator(
ICloner cloner
)
{
protected List<TplWithFleaPrice>? allowedFleaPriceItemsForBarter;
protected RagfairConfig ragfairConfig = configServer.GetConfig<RagfairConfig>();
protected TraderConfig traderConfig = configServer.GetConfig<TraderConfig>();
protected BotConfig botConfig = configServer.GetConfig<BotConfig>();
protected List<TplWithFleaPrice>? allowedFleaPriceItemsForBarter;
/** Internal counter to ensure each offer created has a unique value for its intId property */
protected int offerCounter = 0;
protected RagfairConfig ragfairConfig = configServer.GetConfig<RagfairConfig>();
protected TraderConfig traderConfig = configServer.GetConfig<TraderConfig>();
/**
* Create a flea offer and store it in the Ragfair server offers array
* @param userID Owner of the offer
@@ -31,8 +31,8 @@ public class RepeatableQuestGenerator(
ICloner _cloner
)
{
protected int _maxRandomNumberAttempts = 6;
protected QuestConfig _questConfig = _configServer.GetConfig<QuestConfig>();
protected int _maxRandomNumberAttempts = 6;
/// <summary>
/// This method is called by /GetClientRepeatableQuests/ and creates one element of quest type format (see
@@ -31,9 +31,9 @@ public class ScavCaseRewardGenerator(
ICloner _cloner
)
{
protected List<TemplateItem> _dbAmmoItemsCache = [];
protected List<TemplateItem> _dbItemsCache = [];
protected ScavCaseConfig _scavCaseConfig = _configServer.GetConfig<ScavCaseConfig>();
protected List<TemplateItem> _dbItemsCache = [];
protected List<TemplateItem> _dbAmmoItemsCache = [];
/// <summary>
/// Create an array of rewards that will be given to the player upon completing their scav case build
@@ -6,11 +6,11 @@ namespace Core.Generators.WeaponGen;
[Injectable]
public class InventoryMagGen()
{
private TemplateItem _ammoTemplate;
private TemplateItem _magazineTemplate;
private GenerationData _magCounts;
private BotBaseInventory _pmcInventory;
private TemplateItem _magazineTemplate;
private TemplateItem _weaponTemplate;
private TemplateItem _ammoTemplate;
private BotBaseInventory _pmcInventory;
public InventoryMagGen
(
@@ -11,8 +11,8 @@ namespace Core.Helpers.Dialog.Commando;
[Injectable]
public class SptCommandoCommands : IChatCommand
{
protected LocalisationService _localisationService;
protected List<ISptCommand> _sptCommands;
protected LocalisationService _localisationService;
public SptCommandoCommands(
ConfigServer configServer,
@@ -32,6 +32,18 @@ public class SptCommandoCommands : IChatCommand
}
}
public void RegisterSptCommandoCommand(ISptCommand command)
{
if (_sptCommands.Any((c) => c.GetCommand() == command.GetCommand()))
throw new Exception(
_localisationService.GetText(
"chat-unable_to_register_command_already_registered",
command.GetCommand()
)
);
_sptCommands.Add(command);
}
public string GetCommandPrefix()
{
return "spt";
@@ -53,16 +65,4 @@ public class SptCommandoCommands : IChatCommand
.First((c) => c.GetCommand() == command)
.PerformAction(commandHandler, sessionId, request);
}
public void RegisterSptCommandoCommand(ISptCommand command)
{
if (_sptCommands.Any((c) => c.GetCommand() == command.GetCommand()))
throw new Exception(
_localisationService.GetText(
"chat-unable_to_register_command_already_registered",
command.GetCommand()
)
);
_sptCommands.Add(command);
}
}
@@ -25,8 +25,9 @@ public class GiveSptCommand(
ICloner _cloner
) : ISptCommand
{
private const double _acceptableConfidence = 0.9d;
protected Dictionary<string, SavedCommand> _savedCommand = new();
private static readonly Regex _commandRegex = new(@"^spt give (((([a-z]{2,5}) )?""(.+)""|\w+) )?([0-9]+)$");
private const double _acceptableConfidence = 0.9d;
// Exception for flares
protected readonly HashSet<string> _excludedPresetItems =
@@ -36,8 +37,6 @@ public class GiveSptCommand(
ItemTpl.FLARE_RSP30_REACTIVE_SIGNAL_CARTRIDGE_YELLOW
];
protected Dictionary<string, SavedCommand> _savedCommand = new();
public string GetCommand()
{
return "give";
@@ -16,42 +16,6 @@ public class HelloMessageHandler(
protected List<string> _listOfMessages = ["hello", "hi", "sup", "yo", "hey", "bonjour"];
public int GetPriority()
{
return 100;
}
public bool CanHandle(string message)
{
return _listOfMessages.Contains(message, StringComparer.OrdinalIgnoreCase);
}
public void Process(string sessionId, UserDialogInfo sptFriendUser, PmcData sender)
{
_mailSendService.SendUserMessageToPlayer(
sessionId,
sptFriendUser,
_randomUtil.GetArrayValue(
[
"Howdy",
"Hi",
"Greetings",
"Hello",
"Bonjor",
"Yo",
"Sup",
"Heyyyyy",
"Hey there",
"OH its you",
$"Hello {sender?.Info?.Nickname}"
]
),
[],
null
);
}
public string GetCommand()
{
return "hello";
@@ -92,4 +56,40 @@ public class HelloMessageHandler(
return request.DialogId;
}
public int GetPriority()
{
return 100;
}
public bool CanHandle(string message)
{
return _listOfMessages.Contains(message, StringComparer.OrdinalIgnoreCase);
}
public void Process(string sessionId, UserDialogInfo sptFriendUser, PmcData sender)
{
_mailSendService.SendUserMessageToPlayer(
sessionId,
sptFriendUser,
_randomUtil.GetArrayValue(
[
"Howdy",
"Hi",
"Greetings",
"Hello",
"Bonjor",
"Yo",
"Sup",
"Heyyyyy",
"Hey there",
"OH its you",
$"Hello {sender?.Info?.Nickname}"
]
),
[],
null
);
}
}
@@ -24,6 +24,14 @@ public class SptDialogueChatBot(
{
protected IEnumerable<IChatMessageHandler> _chatMessageHandlers = ChatMessageHandlerSetup(chatMessageHandlers);
private static List<IChatMessageHandler> ChatMessageHandlerSetup(IEnumerable<IChatMessageHandler> components)
{
var chatMessageHandlers = components.ToList();
chatMessageHandlers.Sort((a, b) => a.GetPriority() - b.GetPriority());
return chatMessageHandlers;
}
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
@@ -72,14 +80,6 @@ public class SptDialogueChatBot(
return request.DialogId;
}
private static List<IChatMessageHandler> ChatMessageHandlerSetup(IEnumerable<IChatMessageHandler> components)
{
var chatMessageHandlers = components.ToList();
chatMessageHandlers.Sort((a, b) => a.GetPriority() - b.GetPriority());
return chatMessageHandlers;
}
private string GetUnrecognizedCommandMessage()
{
return "Unknown command.";
+7 -7
View File
@@ -15,9 +15,9 @@ public class HandbookHelper(
ICloner _cloner
)
{
protected LookupCollection _handbookPriceCache = new();
protected ItemConfig _itemConfig = _configServer.GetConfig<ItemConfig>();
protected bool _lookupCacheGenerated = false;
protected LookupCollection _handbookPriceCache = new();
/// <summary>
/// Create an in-memory cache of all items with associated handbook price in handbookPriceCache class
@@ -180,24 +180,24 @@ public class HandbookHelper(
public class LookupItem<T, I>
{
public Dictionary<string, T> ById { get; set; }
public Dictionary<string, List<I>> ByParent { get; set; }
public LookupItem()
{
ById = new Dictionary<string, T>();
ByParent = new Dictionary<string, List<I>>();
}
public Dictionary<string, T> ById { get; set; }
public Dictionary<string, List<I>> ByParent { get; set; }
}
public class LookupCollection
{
public LookupItem<double, string> Items { get; set; }
public LookupItem<string, string> Categories { get; set; }
public LookupCollection()
{
Items = new LookupItem<double, string>();
Categories = new LookupItem<string, string>();
}
public LookupItem<double, string> Items { get; set; }
public LookupItem<string, string> Categories { get; set; }
}
+2 -1
View File
@@ -33,13 +33,14 @@ public class HideoutHelper(
ICloner _cloner
)
{
protected HideoutConfig hideoutConfig = _configServer.GetConfig<HideoutConfig>();
public const string BitcoinFarm = "5d5c205bd582a50d042a3c0e";
public const string CultistCircleCraftId = "66827062405f392b203a44cf";
public const string BitcoinProductionId = "5d5c205bd582a50d042a3c0e";
public const string WaterCollector = "5d5589c1f934db045e6c5492";
public const int MaxSkillPoint = 5000;
protected List<string> _idCheck = [BitcoinFarm, CultistCircleCraftId];
protected HideoutConfig hideoutConfig = _configServer.GetConfig<HideoutConfig>();
/// <summary>
/// Add production to profiles' Hideout.Production array
+1 -1
View File
@@ -18,8 +18,8 @@ public class InRaidHelper(
DatabaseService _databaseService
)
{
protected InRaidConfig _inRaidConfig = _configServer.GetConfig<InRaidConfig>();
protected LostOnDeathConfig _lostOnDeathConfig = _configServer.GetConfig<LostOnDeathConfig>();
protected InRaidConfig _inRaidConfig = _configServer.GetConfig<InRaidConfig>();
protected List<string> _pocketSlots = ["pocket1", "pocket2", "pocket3", "pocket4"];
/// <summary>
+1 -1
View File
@@ -8,9 +8,9 @@ namespace Core.Helpers;
[Injectable]
public class PaymentHelper(ConfigServer _configServer)
{
protected bool _addedCustomMoney;
protected InventoryConfig _inventoryConfig = _configServer.GetConfig<InventoryConfig>();
protected List<string> _moneyTpls = [Money.DOLLARS, Money.EUROS, Money.ROUBLES, Money.GP];
protected bool _addedCustomMoney;
/// <summary>
/// Is the passed in tpl money (also checks custom currencies in inventoryConfig.customMoneyTpls)
+3 -3
View File
@@ -13,14 +13,14 @@ public class PresetHelper(
ICloner _cloner
)
{
protected Dictionary<string, Preset> _defaultEquipmentPresets;
protected Dictionary<string, Preset>? _defaultWeaponPresets;
/// <summary>
/// Preset cache - key = item tpl, value = preset ids
/// </summary>
protected Dictionary<string, HashSet<string>> _lookup = new();
protected Dictionary<string, Preset> _defaultEquipmentPresets;
protected Dictionary<string, Preset>? _defaultWeaponPresets;
public void HydratePresetStore(Dictionary<string, HashSet<string>> input)
{
_lookup = input;
+2 -1
View File
@@ -27,7 +27,6 @@ public class ProfileHelper(
ConfigServer _configServer
)
{
protected readonly List<string> gameEditions = ["edge_of_darkness", "unheard_edition"];
protected InventoryConfig _inventoryConfig = _configServer.GetConfig<InventoryConfig>();
/// <summary>
@@ -558,6 +557,8 @@ public class ProfileHelper(
return pmcProfile?.Info?.Bans?.Any(b => b.BanType == BanType.RAGFAIR && currentTimestamp < b.DateTime) ?? false;
}
protected readonly List<string> gameEditions = ["edge_of_darkness", "unheard_edition"];
public bool HasAccessToRepeatableFreeRefreshSystem(PmcData pmcProfile)
{
return gameEditions.Contains(pmcProfile.Info.GameVersion);
+1 -1
View File
@@ -38,8 +38,8 @@ public class QuestHelper(
ICloner _cloner
)
{
protected List<QuestStatusEnum> _newlyQuestCheck = [QuestStatusEnum.Started, QuestStatusEnum.AvailableForFinish];
protected QuestConfig _questConfig = _configServer.GetConfig<QuestConfig>();
protected List<QuestStatusEnum> _newlyQuestCheck = [QuestStatusEnum.Started, QuestStatusEnum.AvailableForFinish];
/// <summary>
/// Get status of a quest in player profile by its id
+2 -2
View File
@@ -42,9 +42,9 @@ public class RagfairOfferHelper(
EventOutputHolder _eventOutputHolder,
ConfigServer _configServer)
{
protected static string _goodSoldTemplate = "5bdabfb886f7743e152e867e 0"; // Your {soldItem} {itemCount} items were bought by {buyerNickname}.
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected RagfairConfig _ragfairConfig = _configServer.GetConfig<RagfairConfig>();
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected static string _goodSoldTemplate = "5bdabfb886f7743e152e867e 0"; // Your {soldItem} {itemCount} items were bought by {buyerNickname}.
/// <summary>
/// Passthrough to ragfairOfferService.getOffers(), get flea offers a player should see
@@ -28,9 +28,9 @@ public class RagfairServerHelper(
ICloner cloner
)
{
protected static string goodsReturnedTemplate = "5bdabfe486f7743e1665df6e 0"; // Your item was not sold
protected QuestConfig questConfig = configServer.GetConfig<QuestConfig>();
protected RagfairConfig ragfairConfig = configServer.GetConfig<RagfairConfig>();
protected QuestConfig questConfig = configServer.GetConfig<QuestConfig>();
protected static string goodsReturnedTemplate = "5bdabfe486f7743e1665df6e 0"; // Your item was not sold
/**
* Is item valid / on blacklist / quest item
+1 -1
View File
@@ -36,8 +36,8 @@ public class TradeHelper(
ICloner _cloner
)
{
protected InventoryConfig _inventoryConfig = _configServer.GetConfig<InventoryConfig>();
protected TraderConfig _traderConfig = _configServer.GetConfig<TraderConfig>();
protected InventoryConfig _inventoryConfig = _configServer.GetConfig<InventoryConfig>();
/// <summary>
/// Buy item from flea or trader
+1 -1
View File
@@ -32,8 +32,8 @@ public class TraderAssortHelper(
ICloner _cloner
)
{
protected Dictionary<string, Dictionary<string, string>> _mergedQuestAssorts = new();
protected TraderConfig _traderConfig = _configServer.GetConfig<TraderConfig>();
protected Dictionary<string, Dictionary<string, string>> _mergedQuestAssorts = new();
protected bool createdMergedQuestAssorts = false;
/// <summary>
+2 -2
View File
@@ -30,9 +30,9 @@ public class TraderHelper(
ConfigServer _configServer
)
{
protected List<string> _gameVersions = [GameEditions.EDGE_OF_DARKNESS, GameEditions.UNHEARD];
protected Dictionary<string, int?> _highestTraderPriceItems = new();
protected TraderConfig _traderConfig = _configServer.GetConfig<TraderConfig>();
protected Dictionary<string, int?> _highestTraderPriceItems = new();
protected List<string> _gameVersions = [GameEditions.EDGE_OF_DARKNESS, GameEditions.UNHEARD];
/// <summary>
@@ -16,4 +16,3 @@
// TODO: this likely wont be used anymore, so commenting out insteaad of reimplementing
@@ -16,4 +16,3 @@
// TODO: this likely wont be used anymore, so commenting out insteaad of reimplementing
@@ -54,12 +54,6 @@ public record LocaleDetails
public record CreateItemResult
{
public CreateItemResult()
{
Success = false;
Errors = new List<string>();
}
[JsonPropertyName("success")]
public bool? Success { get; set; }
@@ -68,6 +62,12 @@ public record CreateItemResult
[JsonPropertyName("errors")]
public List<string>? Errors { get; set; }
public CreateItemResult()
{
Success = false;
Errors = new List<string>();
}
}
// TODO: This needs to be reworked with however we do it for this project
+47 -47
View File
@@ -5,53 +5,6 @@ namespace Core.Models.Spt.Server;
public record Locations
{
private Dictionary<string, Eft.Common.Location>? _locationDictionaryCache;
// sometimes we get the key or value given so save changing logic in each place
// have it key both
private Dictionary<string, string> _locationMappings = new()
{
// EFT
{ "factory4_day", "Factory4Day" },
{ "bigmap", "Bigmap" },
{ "develop", "Develop" },
{ "factory4_night", "Factory4Night" },
{ "hideout", "Hideout" },
{ "interchange", "Interchange" },
{ "laboratory", "Laboratory" },
{ "lighthouse", "Lighthouse" },
{ "privatearea", "PrivateArea" },
{ "rezervbase", "RezervBase" },
{ "shoreline", "Shoreline" },
{ "suburbs", "Suburbs" },
{ "tarkovstreets", "TarkovStreets" },
{ "terminal", "Terminal" },
{ "town", "Town" },
{ "woods", "Woods" },
{ "sandbox", "Sandbox" },
{ "sandbox_high", "SandboxHigh" },
// SPT
{ "Factory4Day", "Factory4Day" },
{ "Bigmap", "Bigmap" },
{ "Develop", "Develop" },
{ "Factory4Night", "Factory4Night" },
{ "Hideout", "Hideout" },
{ "Interchange", "Interchange" },
{ "Laboratory", "Laboratory" },
{ "Lighthouse", "Lighthouse" },
{ "PrivateArea", "PrivateArea" },
{ "RezervBase", "RezervBase" },
{ "Shoreline", "Shoreline" },
{ "Suburbs", "Suburbs" },
{ "TarkovStreets", "TarkovStreets" },
{ "Terminal", "Terminal" },
{ "Town", "Town" },
{ "Woods", "Woods" },
{ "Sandbox", "Sandbox" },
{ "SandboxHigh", "SandboxHigh" }
};
[JsonPropertyName("bigmap")]
public Eft.Common.Location? Bigmap { get; set; }
@@ -110,6 +63,8 @@ public record Locations
[JsonPropertyName("base")]
public LocationsBase? Base { get; set; }
private Dictionary<string, Eft.Common.Location>? _locationDictionaryCache;
/// <summary>
/// Get map locations as a dictionary, keyed by its name e.g. Factory4Day
/// </summary>
@@ -138,4 +93,49 @@ public record Locations
_locationDictionaryCache = classProps
.ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(this, null) as Eft.Common.Location);
}
// sometimes we get the key or value given so save changing logic in each place
// have it key both
private Dictionary<string, string> _locationMappings = new()
{
// EFT
{ "factory4_day", "Factory4Day" },
{ "bigmap", "Bigmap" },
{ "develop", "Develop" },
{ "factory4_night", "Factory4Night" },
{ "hideout", "Hideout" },
{ "interchange", "Interchange" },
{ "laboratory", "Laboratory" },
{ "lighthouse", "Lighthouse" },
{ "privatearea", "PrivateArea" },
{ "rezervbase", "RezervBase" },
{ "shoreline", "Shoreline" },
{ "suburbs", "Suburbs" },
{ "tarkovstreets", "TarkovStreets" },
{ "terminal", "Terminal" },
{ "town", "Town" },
{ "woods", "Woods" },
{ "sandbox", "Sandbox" },
{ "sandbox_high", "SandboxHigh" },
// SPT
{ "Factory4Day", "Factory4Day" },
{ "Bigmap", "Bigmap" },
{ "Develop", "Develop" },
{ "Factory4Night", "Factory4Night" },
{ "Hideout", "Hideout" },
{ "Interchange", "Interchange" },
{ "Laboratory", "Laboratory" },
{ "Lighthouse", "Lighthouse" },
{ "PrivateArea", "PrivateArea" },
{ "RezervBase", "RezervBase" },
{ "Shoreline", "Shoreline" },
{ "Suburbs", "Suburbs" },
{ "TarkovStreets", "TarkovStreets" },
{ "Terminal", "Terminal" },
{ "Town", "Town" },
{ "Woods", "Woods" },
{ "Sandbox", "Sandbox" },
{ "SandboxHigh", "SandboxHigh" }
};
}
+4 -4
View File
@@ -12,13 +12,13 @@ namespace Core.Routers;
[Injectable]
public class EventOutputHolder
{
protected Dictionary<string, Dictionary<string, bool>> _clientActiveSessionStorage = new();
protected ICloner _cloner;
protected ISptLogger<EventOutputHolder> _logger;
protected Dictionary<string, ItemEventRouterResponse> _outputStore = new();
protected ProfileHelper _profileHelper;
protected TimeUtil _timeUtil;
protected ICloner _cloner;
protected Dictionary<string, ItemEventRouterResponse> _outputStore = new();
protected Dictionary<string, Dictionary<string, bool>> _clientActiveSessionStorage = new();
public EventOutputHolder(
ISptLogger<EventOutputHolder> logger,
+1 -1
View File
@@ -6,8 +6,8 @@ namespace Core.Routers;
[Injectable]
public class HttpRouter
{
protected IEnumerable<DynamicRouter> _dynamicRoutes;
protected IEnumerable<StaticRouter> _staticRouters;
protected IEnumerable<DynamicRouter> _dynamicRoutes;
public HttpRouter(
IEnumerable<StaticRouter> staticRouters,
+1 -1
View File
@@ -8,8 +8,8 @@ namespace Core.Routers;
public class ImageRouter
{
protected FileUtil _fileUtil;
protected HttpFileUtil _httpFileUtil;
protected ImageRouterService _imageRouterService;
protected HttpFileUtil _httpFileUtil;
public ImageRouter(
FileUtil fileUtil,
+6 -6
View File
@@ -13,14 +13,14 @@ namespace Core.Routers;
[Injectable]
public class ItemEventRouter
{
protected ICloner _cloner;
protected EventOutputHolder _eventOutputHolder;
protected HttpResponseUtil _httpResponseUtil;
protected List<ItemEventRouterDefinition> _itemEventRouters;
protected JsonUtil _jsonUtil;
protected LocalisationService _localisationService;
protected ISptLogger<ItemEventRouter> _logger;
protected HttpResponseUtil _httpResponseUtil;
protected JsonUtil _jsonUtil;
protected ProfileHelper _profileHelper;
protected LocalisationService _localisationService;
protected EventOutputHolder _eventOutputHolder;
protected List<ItemEventRouterDefinition> _itemEventRouters;
protected ICloner _cloner;
public ItemEventRouter(
ISptLogger<ItemEventRouter> logger,
@@ -12,8 +12,8 @@ namespace Core.Routers.ItemEvents;
[Injectable(InjectableTypeOverride = typeof(ItemEventRouterDefinition))]
public class CustomizationItemEventRouter : ItemEventRouterDefinition
{
protected CustomizationCallbacks _customizationCallbacks;
protected ISptLogger<CustomizationItemEventRouter> _logger;
protected CustomizationCallbacks _customizationCallbacks;
public CustomizationItemEventRouter
(
@@ -14,8 +14,8 @@ namespace Core.Routers.ItemEvents;
[Injectable(InjectableTypeOverride = typeof(ItemEventRouterDefinition))]
public class InventoryItemEventRouter : ItemEventRouterDefinition
{
protected HideoutCallbacks _hideoutCallbacks;
protected InventoryCallbacks _inventoryCallbacks;
protected HideoutCallbacks _hideoutCallbacks;
public InventoryItemEventRouter
(
+3 -3
View File
@@ -10,11 +10,11 @@ namespace Core.Servers;
[Injectable(InjectionType.Singleton)]
public class ConfigServer
{
protected readonly string[] acceptableFileExtensions = ["json", "jsonc"];
protected FileUtil _fileUtil;
protected JsonUtil _jsonUtil;
protected ISptLogger<ConfigServer> _logger;
protected JsonUtil _jsonUtil;
protected FileUtil _fileUtil;
protected Dictionary<string, object> configs = new();
protected readonly string[] acceptableFileExtensions = ["json", "jsonc"];
public ConfigServer(
ISptLogger<ConfigServer> logger,
@@ -21,16 +21,14 @@ public class SptHttpListener : IHttpListener
// We want to read 1KB at a time, for most request this is already big enough
private const int BodyReadBufferSize = 1024 * 1;
private static readonly ImmutableHashSet<string> SupportedMethods = ["GET", "PUT", "POST"];
protected readonly HttpResponseUtil _httpResponseUtil;
protected readonly JsonUtil _jsonUtil;
protected readonly LocalisationService _localisationService;
protected readonly ISptLogger<SptHttpListener> _logger;
protected readonly ISptLogger<RequestLogger> _requestLogger;
protected readonly HttpRouter _router;
protected readonly IEnumerable<ISerializer> _serializers;
protected readonly ISptLogger<SptHttpListener> _logger;
protected readonly ISptLogger<RequestLogger> _requestLogger;
protected readonly HttpResponseUtil _httpResponseUtil;
protected readonly LocalisationService _localisationService;
protected readonly JsonUtil _jsonUtil;
public SptHttpListener(
HttpRouter httpRouter,
@@ -51,6 +49,8 @@ public class SptHttpListener : IHttpListener
_jsonUtil = jsonUtil;
}
private static readonly ImmutableHashSet<string> SupportedMethods = ["GET", "PUT", "POST"];
public bool CanHandle(string _, HttpRequest req)
{
return SupportedMethods.Contains(req.Method);
+4 -3
View File
@@ -22,12 +22,13 @@ public class SaveServer(
ConfigServer _configServer
)
{
// onLoad = require("../bindings/SaveLoad");
protected readonly Dictionary<string, Func<SptProfile, SptProfile>> onBeforeSaveCallbacks = new();
private Lock _lock = new();
protected string profileFilepath = "user/profiles/";
protected Dictionary<string, SptProfile> profiles = new();
private Lock _lock = new();
// onLoad = require("../bindings/SaveLoad");
protected readonly Dictionary<string, Func<SptProfile, SptProfile>> onBeforeSaveCallbacks = new();
protected Dictionary<string, string> saveMd5 = new();
/**
@@ -22,13 +22,14 @@ public class SptWebSocketConnectionHandler(
IEnumerable<ISptWebSocketMessageHandler> _messageHandlers
) : IWebSocketConnectionHandler
{
protected WsPing _defaultNotification = new();
protected HttpConfig _httpConfig = _configServer.GetConfig<HttpConfig>();
protected Lock _lockObject = new();
protected Dictionary<string, CancellationTokenSource> _receiveTasks = new();
protected Dictionary<string, Timer> _socketAliveTimers = new();
protected Dictionary<string, WebSocket> _sockets = new();
protected Dictionary<string, Timer> _socketAliveTimers = new();
protected Dictionary<string, CancellationTokenSource> _receiveTasks = new();
protected Lock _lockObject = new();
protected WsPing _defaultNotification = new();
public string GetHookUrl()
{
@@ -83,6 +84,22 @@ public class SptWebSocketConnectionHandler(
);
}
private void TimedTask(WebSocket ws, string sessionID)
{
if (_logger.IsLogEnabled(LogLevel.Debug)) _logger.Debug(_localisationService.GetText("websocket-pinging_player", sessionID));
if (ws.State == WebSocketState.Open)
{
var sendTask = ws.SendAsync(
Encoding.UTF8.GetBytes(_jsonUtil.Serialize(_defaultNotification)),
WebSocketMessageType.Text,
true,
CancellationToken.None
);
sendTask.Wait();
}
}
public void SendMessage(string sessionID, WsNotificationEvent output)
{
try
@@ -111,27 +128,6 @@ public class SptWebSocketConnectionHandler(
}
}
public bool IsWebSocketConnected(string sessionID)
{
return _sockets.TryGetValue(sessionID, out var socket) && socket.State == WebSocketState.Open;
}
private void TimedTask(WebSocket ws, string sessionID)
{
if (_logger.IsLogEnabled(LogLevel.Debug)) _logger.Debug(_localisationService.GetText("websocket-pinging_player", sessionID));
if (ws.State == WebSocketState.Open)
{
var sendTask = ws.SendAsync(
Encoding.UTF8.GetBytes(_jsonUtil.Serialize(_defaultNotification)),
WebSocketMessageType.Text,
true,
CancellationToken.None
);
sendTask.Wait();
}
}
private void ReceiveTask(string sessionID, WebSocket ws, CancellationToken cancelToken)
{
List<byte> readBytes = new();
@@ -176,6 +172,11 @@ public class SptWebSocketConnectionHandler(
}
}
public bool IsWebSocketConnected(string sessionID)
{
return _sockets.TryGetValue(sessionID, out var socket) && socket.State == WebSocketState.Open;
}
public WebSocket GetSessionWebSocket(string sessionID)
{
return _sockets[sessionID];
+6 -6
View File
@@ -10,17 +10,17 @@ namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class BackupService
{
protected const string _profileDir = "./user/profiles";
protected ISptLogger<BackupService> _logger;
protected JsonUtil _jsonUtil;
protected TimeUtil _timeUtil;
protected FileUtil _fileUtil;
protected BackupConfig _backupConfig;
protected readonly List<string> _activeServerMods;
protected BackupConfig _backupConfig;
protected const string _profileDir = "./user/profiles";
// Runs Init() every x minutes
protected Timer _backupIntervalTimer;
protected FileUtil _fileUtil;
protected JsonUtil _jsonUtil;
protected ISptLogger<BackupService> _logger;
protected TimeUtil _timeUtil;
public BackupService(
ISptLogger<BackupService> _logger,
@@ -14,11 +14,12 @@ namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class BotEquipmentFilterService
{
protected BotConfig _botConfig;
protected Dictionary<string, EquipmentFilters?> _botEquipmentConfig;
protected BotHelper _botHelper;
protected ISptLogger<BotEquipmentFilterService> _logger;
protected ProfileHelper _profileHelper;
protected BotHelper _botHelper;
protected BotConfig _botConfig;
protected Dictionary<string, EquipmentFilters?> _botEquipmentConfig;
public BotEquipmentFilterService(
ISptLogger<BotEquipmentFilterService> logger,
@@ -12,18 +12,19 @@ namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class BotEquipmentModPoolService
{
private readonly Lock _lock = new();
protected bool _armorPoolGenerated;
protected BotConfig _botConfig;
protected ConfigServer _configServer;
protected DatabaseService _databaseService;
protected ConcurrentDictionary<string, ConcurrentDictionary<string, HashSet<string>>> _gearModPool;
protected ItemHelper _itemHelper;
protected LocalisationService _localisationService;
protected ISptLogger<BotEquipmentModPoolService> _logger;
protected ConcurrentDictionary<string, ConcurrentDictionary<string, HashSet<string>>> _weaponModPool;
protected ItemHelper _itemHelper;
protected DatabaseService _databaseService;
protected LocalisationService _localisationService;
protected ConfigServer _configServer;
protected bool _weaponPoolGenerated;
protected bool _armorPoolGenerated;
protected ConcurrentDictionary<string, ConcurrentDictionary<string, HashSet<string>>> _weaponModPool;
protected ConcurrentDictionary<string, ConcurrentDictionary<string, HashSet<string>>> _gearModPool;
protected BotConfig _botConfig;
private readonly Lock _lock = new();
public BotEquipmentModPoolService(
ISptLogger<BotEquipmentModPoolService> logger,
@@ -11,9 +11,9 @@ public class BotGenerationCacheService(
LocalisationService _localisationService
)
{
protected Dictionary<string, List<BotBase>> _storedBots = new();
protected Queue<BotBase> _activeBotsInRaid = [];
protected object _lock = new();
protected Dictionary<string, List<BotBase>> _storedBots = new();
/**
@@ -21,8 +21,8 @@ public class BotLootCacheService(
ICloner _cloner
)
{
protected object _lock = new();
protected Dictionary<string, BotLootCache> _lootCache = new();
protected object _lock = new();
/// <summary>
/// Remove cached bot loot data
+1 -1
View File
@@ -21,8 +21,8 @@ public class BotNameService(
)
{
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected object _lock = new();
protected HashSet<string> _usedNameCache = new();
protected object _lock = new();
/// <summary>
/// Clear out any entries in Name Set
@@ -13,8 +13,8 @@ public class BundleHashCacheService(
FileUtil _fileUtil
)
{
protected readonly string _bundleHashCachePath = "./user/cache/bundleHashCache.json";
protected Dictionary<string, string> _bundleHashes = new();
protected readonly string _bundleHashCachePath = "./user/cache/bundleHashCache.json";
public string GetStoredValue(string key)
{
@@ -13,8 +13,8 @@ public class ModHashCacheService(
FileUtil _fileUtil
)
{
protected readonly string _modCachePath = "./user/cache/modCache.json";
protected readonly Dictionary<string, string> _modHashes = new();
protected readonly string _modCachePath = "./user/cache/modCache.json";
public string? GetStoredValue(string key)
{
@@ -39,8 +39,8 @@ public class CircleOfCultistService(
ConfigServer _configServer
)
{
protected const string CircleOfCultistSlotId = "CircleOfCultistsGrid1";
protected HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
protected const string CircleOfCultistSlotId = "CircleOfCultistsGrid1";
/// <summary>
/// Start a sacrifice event
+9 -8
View File
@@ -28,8 +28,10 @@ public class FenceService(
ICloner _cloner
)
{
/** Desired baseline counts - Hydrated on initial assort generation as part of generateFenceAssorts() */
protected FenceAssortGenerationValues desiredAssortCounts;
protected TraderConfig traderConfig = configServer.GetConfig<TraderConfig>();
/** Time when some items in assort will be replaced */
protected long nextPartialRefreshTimestamp;
/** Main assorts you see at all rep levels */
protected TraderAssort? fenceAssort = null;
@@ -37,6 +39,9 @@ public class FenceService(
/** Assorts shown on a separate tab when you max out fence rep */
protected TraderAssort? fenceDiscountAssort = null;
/** Desired baseline counts - Hydrated on initial assort generation as part of generateFenceAssorts() */
protected FenceAssortGenerationValues desiredAssortCounts;
protected HashSet<string> fenceItemUpdCompareProperties =
[
"Buff",
@@ -50,11 +55,6 @@ public class FenceService(
"RepairKit"
];
/** Time when some items in assort will be replaced */
protected long nextPartialRefreshTimestamp;
protected TraderConfig traderConfig = configServer.GetConfig<TraderConfig>();
/**
* Replace main fence assort with new assort
@@ -1367,7 +1367,8 @@ public class FenceService(
{
var itemTypeCounts = new Dictionary<string, (int current, int max)>();
foreach (var x in limits.Keys) itemTypeCounts[x] = new ValueTuple<int, int> { current = 0, max = limits[x] };
foreach (var x in limits.Keys)
itemTypeCounts[x] = new(0, limits[x]);
return itemTypeCounts;
}
+4 -4
View File
@@ -6,15 +6,15 @@ namespace Core.Services;
public class I18nService
{
private List<string> _locales;
private Dictionary<string, string> _fallbacks;
private string _defaultLocale;
private string _directory;
private Dictionary<string, string> _fallbacks;
private FileUtil _fileUtil;
private JsonUtil _jsonUtil;
private FileUtil _fileUtil;
private string _setLocale;
private Dictionary<string, LazyLoad<Dictionary<string, string>>> _loadedLocales = new();
private List<string> _locales;
private string _setLocale;
// TODO: try convert to primary ctor
public I18nService(
+1 -1
View File
@@ -13,10 +13,10 @@ public class ItemFilterService(
ConfigServer _configServer
)
{
protected HashSet<string>? _itemBlacklistCache = [];
protected ItemConfig _itemConfig = _configServer.GetConfig<ItemConfig>();
protected HashSet<string>? _lootableItemBlacklistCache = [];
protected HashSet<string>? _itemBlacklistCache = [];
/**
* Check if the provided template id is blacklisted in config/item.json/blacklist
@@ -8,12 +8,12 @@ namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class LocalisationService
{
protected DatabaseServer _databaseServer;
protected I18nService _i18nService;
protected LocaleService _localeService;
protected ISptLogger<LocalisationService> _logger;
protected RandomUtil _randomUtil;
protected DatabaseServer _databaseServer;
protected LocaleService _localeService;
protected I18nService _i18nService;
// TODO: turn into primary ctor
public LocalisationService(
@@ -20,39 +20,39 @@ namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class LocationLifecycleService
{
private readonly ISptLogger<LocationLifecycleService> _logger;
private readonly RewardHelper _rewardHelper;
private readonly ConfigServer _configServer;
private readonly TimeUtil _timeUtil;
private readonly DatabaseService _databaseService;
private readonly ProfileHelper _profileHelper;
private readonly HashUtil _hashUtil;
private readonly ApplicationContext _applicationContext;
private readonly BotGenerationCacheService _botGenerationCacheService;
private readonly BotLootCacheService _botLootCacheService;
private readonly BotNameService _botNameService;
private readonly PmcConfig _pmcConfig;
private readonly ICloner _cloner;
private readonly ConfigServer _configServer;
private readonly DatabaseService _databaseService;
private readonly HashUtil _hashUtil;
private readonly HealthHelper _healthHelper;
private readonly HideoutConfig _hideoutConfig;
private readonly InRaidConfig _inRaidConfig;
private readonly InRaidHelper _inRaidHelper;
private readonly InsuranceService _insuranceService;
private readonly LocalisationService _localisationService;
private readonly LocationConfig _locationConfig;
private readonly RaidTimeAdjustmentService _raidTimeAdjustmentService;
private readonly LocationLootGenerator _locationLootGenerator;
private readonly ISptLogger<LocationLifecycleService> _logger;
private readonly LocalisationService _localisationService;
private readonly BotLootCacheService _botLootCacheService;
private readonly RagfairConfig _ragfairConfig;
private readonly HideoutConfig _hideoutConfig;
private readonly TraderConfig _traderConfig;
private readonly LootGenerator _lootGenerator;
private readonly MailSendService _mailSendService;
private readonly MatchBotDetailsCacheService _matchBotDetailsCacheService;
private readonly PlayerScavGenerator _playerScavGenerator;
private readonly PmcChatResponseService _pmcChatResponseService;
private readonly PmcConfig _pmcConfig;
private readonly ProfileHelper _profileHelper;
private readonly QuestHelper _questHelper;
private readonly RagfairConfig _ragfairConfig;
private readonly RaidTimeAdjustmentService _raidTimeAdjustmentService;
private readonly RandomUtil _randomUtil;
private readonly RewardHelper _rewardHelper;
private readonly SaveServer _saveServer;
private readonly TimeUtil _timeUtil;
private readonly TraderConfig _traderConfig;
private readonly TraderHelper _traderHelper;
private readonly RandomUtil _randomUtil;
private readonly InRaidConfig _inRaidConfig;
private readonly InRaidHelper _inRaidHelper;
private readonly PlayerScavGenerator _playerScavGenerator;
private readonly SaveServer _saveServer;
private readonly HealthHelper _healthHelper;
private readonly PmcChatResponseService _pmcChatResponseService;
private readonly QuestHelper _questHelper;
private readonly InsuranceService _insuranceService;
private readonly MatchBotDetailsCacheService _matchBotDetailsCacheService;
public LocationLifecycleService(
ISptLogger<LocationLifecycleService> logger,
@@ -26,8 +26,8 @@ public class PmcChatResponseService(
MatchBotDetailsCacheService _matchBotDetailsCacheService,
ConfigServer _configServer)
{
protected GiftsConfig _giftConfig = _configServer.GetConfig<GiftsConfig>();
protected PmcChatResponse _pmcResponsesConfig = _configServer.GetConfig<PmcChatResponse>();
protected GiftsConfig _giftConfig = _configServer.GetConfig<GiftsConfig>();
/**
* For each PMC victim of the player, have a chance to send a message to the player, can be positive or negative
+3 -3
View File
@@ -23,13 +23,13 @@ public class PostDbLoadService(
ConfigServer _configServer,
ICloner _cloner)
{
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
protected HideoutConfig _hideoutConfig = _configServer.GetConfig<HideoutConfig>();
protected ItemConfig _itemConfig = _configServer.GetConfig<ItemConfig>();
protected LocationConfig _locationConfig = _configServer.GetConfig<LocationConfig>();
protected LootConfig _lootConfig = _configServer.GetConfig<LootConfig>();
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected ItemConfig _itemConfig = _configServer.GetConfig<ItemConfig>();
protected RagfairConfig _ragfairConfig = _configServer.GetConfig<RagfairConfig>();
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
public void PerformPostDbLoadActions()
{
@@ -28,7 +28,6 @@ public class ProfileFixerService(
InventoryHelper _inventoryHelper
)
{
protected List<string> _areas = ["hideout", "main"];
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
/// <summary>
@@ -437,6 +436,8 @@ public class ProfileFixerService(
foreach (var skill in skills.Where(skill => skill.Progress > 5100)) skill.Progress = 5100;
}
protected List<string> _areas = ["hideout", "main"];
/**
* Checks profile inventory for items that do not exist inside the items db
* @param sessionId Session id
@@ -27,11 +27,11 @@ public class RagfairOfferService(
RagfairOfferHolder ragfairOfferHolder
)
{
protected bool playerOffersLoaded;
/** Offer id + offer object */
protected Dictionary<string, RagfairOffer> expiredOffers = new();
protected bool playerOffersLoaded;
protected RagfairConfig ragfairConfig = configServer.GetConfig<RagfairConfig>();
/**
@@ -25,8 +25,8 @@ public class RagfairPriceService(
ConfigServer _configServer
)
{
private RagfairConfig _ragfairConfig = _configServer.GetConfig<RagfairConfig>();
protected Dictionary<string, double>? _staticPrices;
private RagfairConfig _ragfairConfig = _configServer.GetConfig<RagfairConfig>();
/// <summary>
/// Generate static (handbook) and dynamic (prices.json) flea prices, store inside class as dictionaries
@@ -24,7 +24,15 @@ public class SeasonalEventService(
ConfigServer _configServer
)
{
protected SeasonalEventConfig _seasonalEventConfig = _configServer.GetConfig<SeasonalEventConfig>();
protected QuestConfig _questConfig = _configServer.GetConfig<QuestConfig>();
protected HttpConfig _httpConfig = _configServer.GetConfig<HttpConfig>();
protected WeatherConfig _weatherConfig = _configServer.GetConfig<WeatherConfig>();
protected LocationConfig _locationConfig = _configServer.GetConfig<LocationConfig>();
private List<SeasonalEvent> _currentlyActiveEvents = [];
private bool _christmasEventActive = false;
private bool _halloweenEventActive = false;
protected IReadOnlyList<string> _christmasEventItems =
[
@@ -53,9 +61,6 @@ public class SeasonalEventService(
ItemTpl.FACECOVER_AYBOLIT_MASK
];
private List<SeasonalEvent> _currentlyActiveEvents = [];
private bool _halloweenEventActive = false;
protected IReadOnlyList<string> _halloweenEventItems =
[
ItemTpl.FACECOVER_SPOOKY_SKULL_MASK,
@@ -71,12 +76,6 @@ public class SeasonalEventService(
ItemTpl.FACECOVER_HOCKEY_PLAYER_MASK_QUIET
];
protected HttpConfig _httpConfig = _configServer.GetConfig<HttpConfig>();
protected LocationConfig _locationConfig = _configServer.GetConfig<LocationConfig>();
protected QuestConfig _questConfig = _configServer.GetConfig<QuestConfig>();
protected SeasonalEventConfig _seasonalEventConfig = _configServer.GetConfig<SeasonalEventConfig>();
protected WeatherConfig _weatherConfig = _configServer.GetConfig<WeatherConfig>();
/// <summary>
/// Get an array of christmas items found in bots inventories as loot
/// </summary>
+11 -11
View File
@@ -12,20 +12,20 @@ namespace Core.Utils;
[Injectable(InjectionType.Singleton)]
public class App
{
protected readonly RandomUtil _randomUtil;
protected ConfigServer _configServer;
protected CoreConfig _coreConfig;
protected DatabaseService _databaseService;
protected EncodingUtil _encodingUtil;
protected HttpServer _httpServer;
protected LocalisationService _localisationService;
protected ISptLogger<App> _logger;
protected IEnumerable<OnLoad> _onLoad;
protected IEnumerable<OnUpdate> _onUpdate;
protected Dictionary<string, long> _onUpdateLastRun = new();
protected Timer _timer;
protected CoreConfig _coreConfig;
protected ISptLogger<App> _logger;
protected TimeUtil _timeUtil;
protected readonly RandomUtil _randomUtil;
protected LocalisationService _localisationService;
protected ConfigServer _configServer;
protected EncodingUtil _encodingUtil;
protected HttpServer _httpServer;
protected DatabaseService _databaseService;
protected IEnumerable<OnLoad> _onLoad;
protected IEnumerable<OnUpdate> _onUpdate;
public App(
ISptLogger<App> logger,
@@ -4,9 +4,9 @@ namespace Core.Utils.Collections;
public record ExhaustableArray<T> : IExhaustableArray<T>
{
private ICloner _cloner;
private RandomUtil _randomUtil;
private LinkedList<T>? pool;
private RandomUtil _randomUtil;
private ICloner _cloner;
public ExhaustableArray(
T[]? itemPool,
@@ -23,8 +23,8 @@ namespace Core.Utils.Collections;
/// <typeparam name="V"></typeparam>
public class ProbabilityObjectArray<K, V> : List<ProbabilityObject<K, V>>
{
private readonly ICloner _cloner;
private readonly MathUtil _mathUtil;
private readonly ICloner _cloner;
public ProbabilityObjectArray(
MathUtil mathUtil,
+28 -28
View File
@@ -14,22 +14,22 @@ namespace Core.Utils;
[Injectable(InjectionType.Singleton, InjectableTypeOverride = typeof(OnLoad), TypePriority = OnLoadOrder.Database)]
public class DatabaseImporter : OnLoad
{
protected ConfigServer _configServer;
protected DatabaseServer _databaseServer;
protected EncodingUtil _encodingUtil;
protected FileUtil _fileUtil;
protected HashUtil _hashUtil;
protected ImageRouter _imageRouter;
protected ImporterUtil _importerUtil;
protected LocalisationService _localisationService;
private object hashedFile;
private ValidationResult valid = ValidationResult.UNDEFINED;
private string filepath;
private HttpConfig httpConfig;
protected ISptLogger<DatabaseImporter> _logger;
private string filepath;
private object hashedFile;
private HttpConfig httpConfig;
private ValidationResult valid = ValidationResult.UNDEFINED;
protected LocalisationService _localisationService;
protected DatabaseServer _databaseServer;
protected ImageRouter _imageRouter;
protected EncodingUtil _encodingUtil;
protected HashUtil _hashUtil;
protected ImporterUtil _importerUtil;
protected ConfigServer _configServer;
protected FileUtil _fileUtil;
public DatabaseImporter(
ISptLogger<DatabaseImporter> logger,
@@ -56,6 +56,15 @@ public class DatabaseImporter : OnLoad
httpConfig = _configServer.GetConfig<HttpConfig>();
}
/**
* Get path to spt data
* @returns path to data
*/
public string GetSptDataPath()
{
return "./Assets/";
}
public async Task OnLoad()
{
filepath = GetSptDataPath();
@@ -88,20 +97,6 @@ public class DatabaseImporter : OnLoad
CreateRouteMapping(imageFilePath, "files");
}
public string GetRoute()
{
return "spt-database";
}
/**
* Get path to spt data
* @returns path to data
*/
public string GetSptDataPath()
{
return "./Assets/";
}
private void CreateRouteMapping(string directory, string newBasePath)
{
var directoryContent = GetAllFilesInDirectory(directory);
@@ -168,6 +163,11 @@ public class DatabaseImporter : OnLoad
//}
}
public string GetRoute()
{
return "spt-database";
}
protected bool ValidateFile(string filePathAndName, object fileData)
{
/*
+2 -1
View File
@@ -8,9 +8,10 @@ namespace Core.Utils;
[Injectable(InjectionType.Singleton)]
public class HashUtil
{
protected RandomUtil _randomUtil;
protected Regex MongoIdRegex = new("^[a-fA-F0-9]{24}$");
protected RandomUtil _randomUtil;
public HashUtil(RandomUtil randomUtil)
{
_randomUtil = randomUtil;
+10 -10
View File
@@ -11,17 +11,8 @@ namespace Core.Utils;
[Injectable]
public class HttpResponseUtil
{
protected readonly JsonUtil _jsonUtil;
protected readonly LocalisationService _localisationService;
protected ImmutableList<Regex> _cleanupRegexList =
[
new("[\\b]"),
new("[\\f]"),
new("[\\n]"),
new("[\\r]"),
new("[\\t]")
];
protected readonly JsonUtil _jsonUtil;
public HttpResponseUtil(
JsonUtil jsonUtil,
@@ -32,6 +23,15 @@ public class HttpResponseUtil
_jsonUtil = jsonUtil;
}
protected ImmutableList<Regex> _cleanupRegexList =
[
new("[\\b]"),
new("[\\f]"),
new("[\\n]"),
new("[\\r]"),
new("[\\t]")
];
protected string ClearString(string? s)
{
var value = s ?? "";
+1 -1
View File
@@ -12,9 +12,9 @@ public class ImporterUtil
protected FileUtil _fileUtil;
protected JsonUtil _jsonUtil;
protected ISptLogger<ImporterUtil> _logger;
protected HashSet<string> directoriesToIgnore = ["./Assets/database/locales/server"];
protected HashSet<string> filesToIgnore = ["bearsuits.json", "usecsuits.json", "archivedquests.json"];
protected HashSet<string> directoriesToIgnore = ["./Assets/database/locales/server"];
public ImporterUtil(ISptLogger<ImporterUtil> logger, FileUtil fileUtil, JsonUtil jsonUtil)
{
+2 -2
View File
@@ -2,11 +2,11 @@
public class LazyLoad<T>(Func<T> deserialize)
{
private static readonly TimeSpan _autoCleanerTimeout = TimeSpan.FromSeconds(30);
private bool _isLoaded;
private T? _result;
private bool _isLoaded;
private Timer? autoCleanerTimeout;
private static readonly TimeSpan _autoCleanerTimeout = TimeSpan.FromSeconds(30);
public T? Value
{
+3 -3
View File
@@ -2,10 +2,10 @@ namespace Core.Utils;
public class ProgressWriter
{
protected string? _barEmptyChar;
protected string? _barFillChar;
protected int? _maxBarLength;
protected int _total;
protected int? _maxBarLength;
protected string? _barFillChar;
protected string? _barEmptyChar;
public ProgressWriter(int total, int maxBarLength, string barFillChar, string barEmptyChar)
{
+1 -1
View File
@@ -13,13 +13,13 @@ public class RagfairOfferHolder(
HashUtil hashUtil,
ConfigServer configServer)
{
protected int _maxOffersPerTemplate = (int)configServer.GetConfig<RagfairConfig>().Dynamic.OfferItemCount.Max;
protected Dictionary<string, RagfairOffer> _offersById = new();
protected object _offersByIdLock = new();
protected Dictionary<string, Dictionary<string, RagfairOffer>> _offersByTemplate = new();
protected object _offersByTemplateLock = new();
protected Dictionary<string, Dictionary<string, RagfairOffer>> _offersByTrader = new();
protected object _offersByTraderLock = new();
protected int _maxOffersPerTemplate = (int)configServer.GetConfig<RagfairConfig>().Dynamic.OfferItemCount.Max;
public RagfairOffer? GetOfferById(string id)
{
+2 -3
View File
@@ -10,7 +10,9 @@ namespace Core.Utils;
[Injectable(InjectionType.Singleton)]
public class RandomUtil(ISptLogger<RandomUtil> _logger, ICloner _cloner)
{
public readonly Random Random = new();
private const int DecimalPointRandomPrecision = 6;
private static readonly int DecimalPointRandomPrecisionMultiplier = (int)Math.Pow(10, DecimalPointRandomPrecision);
/// <summary>
/// The IEEE-754 standard for double-precision floating-point numbers limits the number of digits (including both
@@ -18,9 +20,6 @@ public class RandomUtil(ISptLogger<RandomUtil> _logger, ICloner _cloner)
/// </summary>
public const int MaxSignificantDigits = 15;
private static readonly int DecimalPointRandomPrecisionMultiplier = (int)Math.Pow(10, DecimalPointRandomPrecision);
public readonly Random Random = new();
/// <summary>
/// Generates a random integer between the specified minimum and maximum values, inclusive.
/// </summary>
+6 -6
View File
@@ -12,8 +12,8 @@ namespace Core.Utils;
public class WatermarkLocale
{
protected List<string> description;
protected List<string> modding;
protected List<string> warning;
protected List<string> modding;
public WatermarkLocale(LocalisationService localisationService)
{
@@ -65,15 +65,15 @@ public class WatermarkLocale
[Injectable]
public class Watermark
{
protected ConfigServer _configServer;
protected LocalisationService _localisationService;
protected ISptLogger<Watermark> _logger;
protected WatermarkLocale _watermarkLocale;
protected CoreConfig sptConfig;
protected List<string> text = [];
protected string versionLabel = "";
protected ISptLogger<Watermark> _logger;
protected ConfigServer _configServer;
protected LocalisationService _localisationService;
protected WatermarkLocale _watermarkLocale;
public Watermark(
ISptLogger<Watermark> logger,
ConfigServer configServer,
@@ -6,9 +6,6 @@ namespace SptDependencyInjection;
public static class DependencyInjectionRegistrator
{
private static List<Type>? _allLoadedTypes;
private static List<ConstructorInfo>? _allConstructors;
public static void RegisterModOverrideComponents(IServiceCollection builderServices, List<Assembly> assemblies)
{
// We get all the services from this assembly first, since mods will override them later
@@ -56,6 +53,9 @@ public static class DependencyInjectionRegistrator
);
}
private static List<Type>? _allLoadedTypes;
private static List<ConstructorInfo>? _allConstructors;
private static void RegisterGenericComponents(IServiceCollection builderServices, RegisterableType valueTuple)
{
_allLoadedTypes ??= AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).ToList();
+7 -7
View File
@@ -5,6 +5,13 @@ namespace Server.Logger;
public abstract class AbstractFormatter : ITextFormatter
{
protected abstract string ProcessText(string text);
protected virtual string GetFormattedText(string timestamp, string logLevel, string sourceContext, string message)
{
return $"[{timestamp} {logLevel}][{sourceContext}] {message}";
}
public void Format(LogEvent logEvent, TextWriter output)
{
var newLine = Environment.NewLine;
@@ -16,11 +23,4 @@ public abstract class AbstractFormatter : ITextFormatter
var logMessage = ProcessText(GetFormattedText(timestamp, logLevel, sourceContext, $"{message}{exception}"));
output.WriteLine(logMessage);
}
protected abstract string ProcessText(string text);
protected virtual string GetFormattedText(string timestamp, string logLevel, string sourceContext, string message)
{
return $"[{timestamp} {logLevel}][{sourceContext}] {message}";
}
}
+2 -2
View File
@@ -2,8 +2,6 @@ namespace Server.Logger;
public class ConsoleFormatter : AbstractFormatter
{
public static ConsoleFormatter Default { get; } = new();
protected override string ProcessText(string text)
{
return text;
@@ -13,4 +11,6 @@ public class ConsoleFormatter : AbstractFormatter
{
return message;
}
public static ConsoleFormatter Default { get; } = new();
}
+2 -2
View File
@@ -4,11 +4,11 @@ namespace Server.Logger;
public class FileFormatter : AbstractFormatter
{
public static FileFormatter Default { get; } = new();
protected override string ProcessText(string message)
{
foreach (Match match in Regex.Matches(message, @"\x1b\[[0-9]{1,2}(;[0-1]{1,2}){0,1}m")) message = message.Replace(match.Value, "");
return message.Replace("\"", "");
}
public static FileFormatter Default { get; } = new();
}
+18 -18
View File
@@ -29,6 +29,24 @@ public class SptWebApplicationLogger<T> : ISptLogger<T>
_logger.LogInformation(ex, data);
}
private string GetColorizedText(
string data,
LogTextColor? textColor = null,
LogBackgroundColor? backgroundColor = null
)
{
var colorString = string.Empty;
if (textColor != null)
colorString += ((int)textColor.Value).ToString();
if (backgroundColor != null)
colorString += string.IsNullOrEmpty(colorString)
? ((int)backgroundColor.Value).ToString()
: $";{((int)backgroundColor.Value).ToString()}";
return $"\x1b[{colorString}m{data}\x1b[0m";
}
public void Success(string data, Exception? ex = null)
{
_logger.LogInformation(ex, GetColorizedText(data, LogTextColor.Green));
@@ -70,24 +88,6 @@ public class SptWebApplicationLogger<T> : ISptLogger<T>
return _logger.IsEnabled(ConvertLogLevel(level));
}
private string GetColorizedText(
string data,
LogTextColor? textColor = null,
LogBackgroundColor? backgroundColor = null
)
{
var colorString = string.Empty;
if (textColor != null)
colorString += ((int)textColor.Value).ToString();
if (backgroundColor != null)
colorString += string.IsNullOrEmpty(colorString)
? ((int)backgroundColor.Value).ToString()
: $";{((int)backgroundColor.Value).ToString()}";
return $"\x1b[{colorString}m{data}\x1b[0m";
}
protected Microsoft.Extensions.Logging.LogLevel ConvertLogLevel(LogLevel level)
{
return level switch
+2 -2
View File
@@ -22,10 +22,10 @@ public class ItemTplGenerator(
IEnumerable<OnLoad> _onLoadComponents
)
{
private HashSet<string> collidedEnumKeys = [];
private string enumDir;
private IDictionary<string, string> itemOverrides;
private Dictionary<string, TemplateItem> items;
private IDictionary<string, string> itemOverrides;
private HashSet<string> collidedEnumKeys = [];
public async Task Run()
{
+10 -10
View File
@@ -6,6 +6,16 @@ namespace UnitTests.Mock;
public class MockLogger<T> : ISptLogger<T>
{
public void LogWithColor(
string data,
Exception? ex = null,
LogTextColor? textColor = null,
LogBackgroundColor? backgroundColor = null
)
{
Console.WriteLine(data);
}
public void LogWithColor(string data, LogTextColor? textColor = null, LogBackgroundColor? backgroundColor = null, Exception? ex = null)
{
throw new NotImplementedException();
@@ -51,16 +61,6 @@ public class MockLogger<T> : ISptLogger<T>
return true;
}
public void LogWithColor(
string data,
Exception? ex = null,
LogTextColor? textColor = null,
LogBackgroundColor? backgroundColor = null
)
{
Console.WriteLine(data);
}
public void WriteToLogFile(object body)
{
Console.WriteLine(body);