From 077f86ac46d12e97e9b8a2f6749eb23adffa5275 Mon Sep 17 00:00:00 2001 From: CWX Date: Sat, 18 Jan 2025 20:32:59 +0000 Subject: [PATCH] primary ctor for services, servers, loaders --- Core/Loaders/PostDBModLoader.cs | 19 +- Core/Loaders/PostSptModLoader.cs | 18 +- Core/Servers/SaveServer.cs | 46 +-- Core/Servers/WebSocketServer.cs | 22 +- .../DefaultSptWebSocketMessageHandler.cs | 13 +- .../Ws/SptWebSocketConnectionHandler.cs | 41 +-- Core/Services/BotEquipmentFilterService.cs | 21 +- Core/Services/BotLootCacheService.cs | 83 +++--- Core/Services/BotNameService.cs | 56 ++-- Core/Services/BotWeaponModLimitService.cs | 25 +- Core/Services/CreateProfileService.cs | 272 +++++++++--------- Core/Services/DatabaseService.cs | 89 +++--- Core/Services/FenceService.cs | 14 +- Core/Services/GiftService.cs | 61 ++-- Core/Services/I18nService.cs | 2 +- Core/Services/ItemBaseClassService.cs | 23 +- Core/Services/ItemFilterService.cs | 32 +-- Core/Services/LocaleService.cs | 19 +- Core/Services/LocalisationService.cs | 2 +- Core/Services/MailSendService.cs | 156 +++++----- Core/Services/MapMarkerService.cs | 22 +- Core/Services/MatchBotDetailsCacheService.cs | 67 ++--- Core/Services/ProfileActivityService.cs | 14 +- Core/Services/ProfileFixerService.cs | 85 +++--- Core/Services/RagfairPriceService.cs | 24 +- Core/Services/RaidWeatherService.cs | 51 ++-- Core/Services/SeasonalEventService.cs | 98 +++---- .../TraderPurchasePersisterService.cs | 58 ++-- 28 files changed, 590 insertions(+), 843 deletions(-) diff --git a/Core/Loaders/PostDBModLoader.cs b/Core/Loaders/PostDBModLoader.cs index e51034cc..c370d300 100644 --- a/Core/Loaders/PostDBModLoader.cs +++ b/Core/Loaders/PostDBModLoader.cs @@ -3,24 +3,14 @@ using Core.DI; using Core.Models.External; using Core.Models.Utils; - namespace Core.Loaders; [Injectable(InjectableTypeOverride = typeof(OnLoad), TypePriority = OnLoadOrder.PostDBModLoader)] -public class PostDBModLoader : OnLoad +public class PostDBModLoader( + ISptLogger _logger, + IEnumerable _postDbLoadMods +) : OnLoad { - protected ISptLogger _logger; - protected IEnumerable _postDbLoadMods; - - public PostDBModLoader( - ISptLogger logger, - IEnumerable postDbLoadMods - ) - { - _logger = logger; - _postDbLoadMods = postDbLoadMods; - } - public async Task OnLoad() { _logger.Info("Loading PostDBLoadMod..."); @@ -28,6 +18,7 @@ public class PostDBModLoader : OnLoad { postDbLoadMod.PostDBLoad(); } + _logger.Info("Finished loading PostDBLoadMod..."); } diff --git a/Core/Loaders/PostSptModLoader.cs b/Core/Loaders/PostSptModLoader.cs index 6af8edba..17f54517 100644 --- a/Core/Loaders/PostSptModLoader.cs +++ b/Core/Loaders/PostSptModLoader.cs @@ -7,20 +7,11 @@ using Core.Models.Utils; namespace Core.Loaders; [Injectable(InjectableTypeOverride = typeof(OnLoad), TypePriority = OnLoadOrder.PostSptModLoader)] -public class PostSptModLoader : OnLoad +public class PostSptModLoader( + ISptLogger _logger, + IEnumerable _postSptLoadMods +) : OnLoad { - protected ISptLogger _logger; - protected IEnumerable _postSptLoadMods; - - public PostSptModLoader( - ISptLogger logger, - IEnumerable postSptLoadMods - ) - { - _logger = logger; - _postSptLoadMods = postSptLoadMods; - } - public async Task OnLoad() { // if (ProgramStatics.MODS) { @@ -31,6 +22,7 @@ public class PostSptModLoader : OnLoad { postSptLoadMod.PostSptLoad(); } + _logger.Info("Finished loading PostSptMods..."); } diff --git a/Core/Servers/SaveServer.cs b/Core/Servers/SaveServer.cs index 9eb8bff0..b77cf8eb 100644 --- a/Core/Servers/SaveServer.cs +++ b/Core/Servers/SaveServer.cs @@ -14,7 +14,15 @@ using Core.Utils; namespace Core.Servers; [Injectable(InjectionType.Singleton)] -public class SaveServer +public class SaveServer( + FileUtil _vfs, + IEnumerable _saveLoadRouters, + JsonUtil _jsonUtil, + HashUtil _hashUtil, + LocalisationService _localisationService, + ISptLogger _logger, + ConfigServer _configServer +) { protected string profileFilepath = "user/profiles/"; @@ -24,33 +32,6 @@ public class SaveServer protected readonly Dictionary> onBeforeSaveCallbacks = new(); protected Dictionary saveMd5 = new(); - protected readonly FileUtil _vfs; - protected readonly IEnumerable _saveLoadRouters; - protected readonly JsonUtil _jsonUtil; - protected readonly HashUtil _hashUtil; - protected readonly LocalisationService _localisationService; - protected readonly ISptLogger _logger; - protected readonly ConfigServer _configServer; - - public SaveServer( - FileUtil vfs, - IEnumerable saveLoadRouters, - JsonUtil jsonUtil, - HashUtil hashUtil, - LocalisationService localisationService, - ISptLogger logger, - ConfigServer configServer - ) - { - _vfs = vfs; - _saveLoadRouters = saveLoadRouters; - _jsonUtil = jsonUtil; - _hashUtil = hashUtil; - _localisationService = localisationService; - _logger = logger; - _configServer = configServer; - } - /** * Add callback to occur prior to saving profile changes * @param id Id for save callback @@ -171,12 +152,14 @@ public class SaveServer throw new Exception($"profile already exists for sessionId: {profileInfo.ProfileId}"); } - profiles.Add(profileInfo.ProfileId, + profiles.Add( + profileInfo.ProfileId, new SptProfile() { ProfileInfo = profileInfo, CharacterData = new Characters() { PmcData = new(), ScavData = new() } - }); + } + ); } /** @@ -204,7 +187,8 @@ public class SaveServer } // Run callbacks - foreach (var callback in _saveLoadRouters) // HealthSaveLoadRouter, InraidSaveLoadRouter, InsuranceSaveLoadRouter, ProfileSaveLoadRouter. THESE SHOULD EXIST IN HERE + foreach (var callback in + _saveLoadRouters) // HealthSaveLoadRouter, InraidSaveLoadRouter, InsuranceSaveLoadRouter, ProfileSaveLoadRouter. THESE SHOULD EXIST IN HERE { profiles[sessionID] = callback.HandleLoad(GetProfile(sessionID)); } diff --git a/Core/Servers/WebSocketServer.cs b/Core/Servers/WebSocketServer.cs index 7038aeb7..40620d7c 100644 --- a/Core/Servers/WebSocketServer.cs +++ b/Core/Servers/WebSocketServer.cs @@ -8,23 +8,12 @@ using Core.Utils; namespace Core.Servers; [Injectable(InjectionType.Singleton)] -public class WebSocketServer +public class WebSocketServer( + IEnumerable _webSocketConnectionHandler, + ISptLogger _logger, + JsonUtil _jsonUtil +) { - protected IEnumerable _webSocketConnectionHandler; - protected ISptLogger _logger; - protected JsonUtil _jsonUtil; - - public WebSocketServer( - IEnumerable webSocketConnectionHandlers, - ISptLogger logger, - JsonUtil jsonUtil - ) - { - _webSocketConnectionHandler = webSocketConnectionHandlers; - _logger = logger; - _jsonUtil = jsonUtil; - } - public async Task OnConnection(HttpContext httpContext) { var socket = await httpContext.WebSockets.AcceptWebSocketAsync(); @@ -48,6 +37,7 @@ public class WebSocketServer wsh.OnConnection(webSocket, context).Wait(); _logger.Info($"WebSocketHandler \"{wsh.GetSocketId()}\" connected"); } + return Task.CompletedTask; } } diff --git a/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs b/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs index c0d6974b..cf04c2b5 100644 --- a/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs +++ b/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs @@ -5,17 +5,10 @@ using Core.Annotations; namespace Core.Servers.Ws.Message; [Injectable] -public class DefaultSptWebSocketMessageHandler : ISptWebSocketMessageHandler +public class DefaultSptWebSocketMessageHandler( + Models.Utils.ISptLogger _logger +) : ISptWebSocketMessageHandler { - protected Models.Utils.ISptLogger _logger; - - public DefaultSptWebSocketMessageHandler( - Models.Utils.ISptLogger logger - ) - { - _logger = logger; - } - public async Task OnSptMessage(string sessionID, WebSocket client, byte[] rawData) { _logger.Debug($"[{sessionID}] SPT message received: {Encoding.UTF8.GetString(rawData)}"); diff --git a/Core/Servers/Ws/SptWebSocketConnectionHandler.cs b/Core/Servers/Ws/SptWebSocketConnectionHandler.cs index 6be513b9..70ef5fc6 100644 --- a/Core/Servers/Ws/SptWebSocketConnectionHandler.cs +++ b/Core/Servers/Ws/SptWebSocketConnectionHandler.cs @@ -12,39 +12,24 @@ using Core.Utils; namespace Core.Servers.Ws; [Injectable(InjectionType.Singleton)] -public class SptWebSocketConnectionHandler : IWebSocketConnectionHandler +public class SptWebSocketConnectionHandler( + ISptLogger _logger, + LocalisationService _localisationService, + JsonUtil _jsonUtil, + ProfileHelper _profileHelper, + ConfigServer _configServer, + IEnumerable _messageHandlers +) : IWebSocketConnectionHandler { + protected HttpConfig _httpConfig = _configServer.GetConfig(); + protected Dictionary _sockets = new(); protected Dictionary _socketAliveTimers = new(); protected Dictionary _receiveTasks = new(); - protected object _lockObject = new(); - - protected ISptLogger _logger; - protected LocalisationService _localisationService; - protected JsonUtil _jsonUtil; - protected ProfileHelper _profileHelper; - protected HttpConfig _httpConfig; - protected IEnumerable _messageHandlers; + protected Lock _lockObject = new(); protected WsPing _defaultNotification = new(); - public SptWebSocketConnectionHandler( - ISptLogger logger, - LocalisationService localisationService, - JsonUtil jsonUtil, - ProfileHelper profileHelper, - ConfigServer configServer, - IEnumerable messageHandlers - ) - { - _logger = logger; - _localisationService = localisationService; - _jsonUtil = jsonUtil; - _profileHelper = profileHelper; - _messageHandlers = messageHandlers; - _httpConfig = configServer.GetConfig(); - } - public string GetHookUrl() => "/notifierServer/getwebsocket/"; public string GetSocketId() => "SPT WebSocket Handler"; @@ -73,7 +58,7 @@ public class SptWebSocketConnectionHandler : IWebSocketConnectionHandler { Thread.Sleep(1000); } - + // Once the websocket dies, we dispose of it _logger.Debug(_localisationService.GetText("websocket-socket_lost_deleting_handle")); lock (_lockObject) @@ -92,7 +77,7 @@ public class SptWebSocketConnectionHandler : IWebSocketConnectionHandler private void TimedTask(WebSocket ws, string sessionID) { _logger.Debug(_localisationService.GetText("websocket-pinging_player", sessionID)); - + if (ws.State == WebSocketState.Open) { var sendTask = ws.SendAsync( diff --git a/Core/Services/BotEquipmentFilterService.cs b/Core/Services/BotEquipmentFilterService.cs index 42f23d97..c194f010 100644 --- a/Core/Services/BotEquipmentFilterService.cs +++ b/Core/Services/BotEquipmentFilterService.cs @@ -8,18 +8,11 @@ using Core.Servers; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class BotEquipmentFilterService +public class BotEquipmentFilterService( + ConfigServer _configServer +) { - protected ConfigServer _configServer; - protected BotConfig _botConfig; - - public BotEquipmentFilterService( - ConfigServer configServer) - { - _configServer = configServer; - - _botConfig = _configServer.GetConfig(); - } + protected BotConfig _botConfig = _configServer.GetConfig(); /// /// Filter a bots data to exclude equipment and cartridges defines in the botConfig @@ -80,7 +73,8 @@ public class BotEquipmentFilterService { var botEquipmentSettings = _botConfig.Equipment[botEquipmentRole]; - if (botEquipmentSettings is null) { + if (botEquipmentSettings is null) + { return null; } @@ -98,7 +92,8 @@ public class BotEquipmentFilterService var blacklistDetailsForBot = _botConfig.Equipment.GetValueOrDefault(botRole, null); return blacklistDetailsForBot?.Blacklist?.FirstOrDefault( - (equipmentFilter) => playerLevel >= equipmentFilter.LevelRange.Min && playerLevel <= equipmentFilter.LevelRange.Max); + (equipmentFilter) => playerLevel >= equipmentFilter.LevelRange.Min && playerLevel <= equipmentFilter.LevelRange.Max + ); } /// diff --git a/Core/Services/BotLootCacheService.cs b/Core/Services/BotLootCacheService.cs index f1cf318c..4e2ceec7 100644 --- a/Core/Services/BotLootCacheService.cs +++ b/Core/Services/BotLootCacheService.cs @@ -12,34 +12,17 @@ using Core.Utils.Cloners; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class BotLootCacheService +public class BotLootCacheService( + ISptLogger _logger, + ItemHelper _itemHelper, + PMCLootGenerator _pmcLootGenerator, + LocalisationService _localisationService, + RagfairPriceService _ragfairPriceService, + ICloner _cloner +) { - protected ISptLogger _logger; - protected ItemHelper _itemHelper; - protected PMCLootGenerator _pmcLootGenerator; - protected LocalisationService _localisationService; - protected RagfairPriceService _ragfairPriceService; - protected ICloner _cloner; - protected Dictionary _lootCache = new(); - public BotLootCacheService( - ISptLogger logger, - ItemHelper itemHelper, - PMCLootGenerator pmcLootGenerator, - LocalisationService localisationService, - RagfairPriceService ragfairPriceService, - ICloner cloner - ) - { - _logger = logger; - _itemHelper = itemHelper; - _pmcLootGenerator = pmcLootGenerator; - _localisationService = localisationService; - _ragfairPriceService = ragfairPriceService; - _cloner = cloner; - } - /// /// Remove cached bot loot data /// @@ -477,7 +460,8 @@ public class BotLootCacheService /// items to add to combined pool if unique protected void AddUniqueItemsToPool(List poolToAddTo, List itemsToAdd) { - if (poolToAddTo.Count() == 0) { + if (poolToAddTo.Count() == 0) + { poolToAddTo.AddRange(itemsToAdd); return; } @@ -488,9 +472,11 @@ public class BotLootCacheService protected void AddItemsToPool(Dictionary poolToAddTo, Dictionary poolOfItemsToAdd) { - foreach (var tpl in poolOfItemsToAdd) { + foreach (var tpl in poolOfItemsToAdd) + { // Skip adding items that already exist - if (poolToAddTo.ContainsKey(tpl.Key)) { + if (poolToAddTo.ContainsKey(tpl.Key)) + { continue; } @@ -569,21 +555,22 @@ public class BotLootCacheService /// Bot role to hydrate protected void InitCacheForBotRole(string botRole) { - _lootCache[botRole] = new () { - BackpackLoot = new (), - PocketLoot = new (), - VestLoot = new (), - SecureLoot = new (), - CombinedPoolLoot = new (), + _lootCache[botRole] = new() + { + BackpackLoot = new(), + PocketLoot = new(), + VestLoot = new(), + SecureLoot = new(), + CombinedPoolLoot = new(), - SpecialItems = new (), - GrenadeItems = new (), - DrugItems = new (), - FoodItems = new (), - DrinkItems = new (), - CurrencyItems = new (), - HealingItems = new (), - StimItems = new (), + SpecialItems = new(), + GrenadeItems = new(), + DrugItems = new(), + FoodItems = new(), + DrinkItems = new(), + CurrencyItems = new(), + HealingItems = new(), + StimItems = new(), }; } @@ -596,19 +583,23 @@ public class BotLootCacheService protected int CompareByValue(int itemAPrice, int itemBPrice) { // If item A has no price, it should be moved to the back when sorting - if (itemAPrice is 0) { + if (itemAPrice is 0) + { return 1; } - if (itemBPrice is 0) { + if (itemBPrice is 0) + { return -1; } - if (itemAPrice < itemBPrice) { + if (itemAPrice < itemBPrice) + { return -1; } - if (itemAPrice > itemBPrice) { + if (itemAPrice > itemBPrice) + { return 1; } diff --git a/Core/Services/BotNameService.cs b/Core/Services/BotNameService.cs index 7acd24ff..e3e91ec6 100644 --- a/Core/Services/BotNameService.cs +++ b/Core/Services/BotNameService.cs @@ -6,47 +6,27 @@ using Core.Models.Enums; using Core.Models.Spt.Config; using Core.Models.Utils; using Core.Servers; - using Core.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class BotNameService +public class BotNameService( + ISptLogger _logger, + BotHelper _botHelper, + RandomUtil _randomUtil, + LocalisationService _localisationService, + DatabaseService _databaseService, + ConfigServer _configServer +) { - protected ISptLogger _logger; - protected BotHelper _botHelper; - protected RandomUtil _randomUtil; - protected LocalisationService _localisationService; - protected DatabaseService _databaseService; - protected ConfigServer _configServer; - protected BotConfig _botConfig; - - protected HashSet _usedNameCache; - - public BotNameService( - ISptLogger logger, - BotHelper botHelper, - RandomUtil randomUtil, - LocalisationService localisationService, - DatabaseService databaseService, - ConfigServer configServer) - { - _logger = logger; - _botHelper = botHelper; - _randomUtil = randomUtil; - _localisationService = localisationService; - _databaseService = databaseService; - _configServer = configServer; - - _botConfig = _configServer.GetConfig(); - _usedNameCache = new HashSet(); - } + protected BotConfig _botConfig = _configServer.GetConfig(); + protected HashSet _usedNameCache = new HashSet(); /// /// Clear out any entries in Name Set /// - public void ClearNameCache() + public void ClearNameCache() { throw new NotImplementedException(); } @@ -78,21 +58,21 @@ public class BotNameService // Get bot name with leading/trailing whitespace removed var name = (isPmc.GetValueOrDefault(false)) // Explicit handling of PMCs, all other bots will get "first_name last_name" ? _botHelper.GetPmcNicknameOfMaxLength(_botConfig.BotNameLengthLimit, botGenerationDetails.Side) - : $"{ _randomUtil.GetArrayValue(botJsonTemplate.FirstNames)} {_randomUtil.GetArrayValue(botJsonTemplate.LastNames)}"; + : $"{_randomUtil.GetArrayValue(botJsonTemplate.FirstNames)} {_randomUtil.GetArrayValue(botJsonTemplate.LastNames)}"; name = name.Trim(); // Config is set to add role to end of bot name if (showTypeInNickname) { - name += $" { botRole}"; + name += $" {botRole}"; } // Replace pmc bot names with player name + prefix if (botGenerationDetails.IsPmc.GetValueOrDefault(false) && botGenerationDetails.AllPmcsHaveSameNameAsPlayer.GetValueOrDefault(false)) { var prefix = _localisationService.GetRandomTextThatMatchesPartialKey("pmc-name_prefix_"); - name = $"{prefix} { name}"; + name = $"{prefix} {name}"; } // Is this a role that must be unique @@ -106,8 +86,8 @@ public class BotNameService if (attempts >= 5) { // 5 attempts to generate a name, pool probably isn't big enough - var genericName = $"{ botGenerationDetails.Side} { _randomUtil.GetInt(100000, 999999)}"; - _logger.Debug($"Failed to find unique name for: { botRole} ${ botGenerationDetails.Side} after 5 attempts, using: ${ genericName}"); + var genericName = $"{botGenerationDetails.Side} {_randomUtil.GetInt(100000, 999999)}"; + _logger.Debug($"Failed to find unique name for: {botRole} ${botGenerationDetails.Side} after 5 attempts, using: ${genericName}"); return genericName; } @@ -133,7 +113,7 @@ public class BotNameService /// Add random PMC name to bots MainProfileNickname property /// /// Bot to update - public void AddRandomPmcNameToBotMainProfileNicknameProperty(BotBase bot) + public void AddRandomPmcNameToBotMainProfileNicknameProperty(BotBase bot) { // Simulate bot looking like a player scav with the PMC name in brackets. // E.g. "ScavName (PMC Name)" @@ -144,7 +124,7 @@ public class BotNameService /// Choose a random PMC name from bear or usec bot jsons /// /// PMC name as string - protected string GetRandomPmcName() + protected string GetRandomPmcName() { var bots = _databaseService.GetBots().Types; diff --git a/Core/Services/BotWeaponModLimitService.cs b/Core/Services/BotWeaponModLimitService.cs index de542365..3e857117 100644 --- a/Core/Services/BotWeaponModLimitService.cs +++ b/Core/Services/BotWeaponModLimitService.cs @@ -10,26 +10,13 @@ using Core.Servers; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class BotWeaponModLimitService +public class BotWeaponModLimitService( + ISptLogger _logger, + ConfigServer _configServer, + ItemHelper _itemHelper +) { - private readonly ISptLogger _logger; - private readonly ConfigServer _configServer; - private readonly ItemHelper _itemHelper; - - private readonly BotConfig _botConfig; - - public BotWeaponModLimitService - ( - ISptLogger logger, - ConfigServer configServer, - ItemHelper itemHelper - ) - { - _logger = logger; - _configServer = configServer; - _itemHelper = itemHelper; - _botConfig = _configServer.GetConfig(); - } + protected BotConfig _botConfig = _configServer.GetConfig(); /// /// Initalise mod limits to be used when generating a weapon diff --git a/Core/Services/CreateProfileService.cs b/Core/Services/CreateProfileService.cs index cb156789..59039af2 100644 --- a/Core/Services/CreateProfileService.cs +++ b/Core/Services/CreateProfileService.cs @@ -16,58 +16,24 @@ using Core.Utils.Cloners; namespace Core.Services; [Injectable] -public class CreateProfileService +public class CreateProfileService( + ISptLogger _logger, + TimeUtil _timeUtil, + HashUtil _hashUtil, + DatabaseService _databaseService, + LocalisationService _localisationService, + ProfileHelper _profileHelper, + ItemHelper _itemHelper, + TraderHelper _traderHelper, + QuestHelper _questHelper, + QuestRewardHelper _questRewardHelper, + ProfileFixerService _profileFixerService, + SaveServer _saveServer, + EventOutputHolder _eventOutputHolder, + PlayerScavGenerator _playerScavGenerator, + ICloner _cloner +) { - protected ISptLogger _logger; - protected TimeUtil _timeUtil; - protected HashUtil _hashUtil; - protected DatabaseService _databaseService; - protected LocalisationService _localisationService; - protected ProfileHelper _profileHelper; - protected ItemHelper _itemHelper; - protected TraderHelper _traderHelper; - protected QuestHelper _questHelper; - protected QuestRewardHelper _questRewardHelper; - protected ProfileFixerService _profileFixerService; - protected SaveServer _saveServer; - protected EventOutputHolder _eventOutputHolder; - protected PlayerScavGenerator _playerScavGenerator; - protected ICloner _cloner; - - public CreateProfileService( - ISptLogger logger, - TimeUtil timeUtil, - HashUtil hashUtil, - DatabaseService databaseService, - LocalisationService localisationService, - ProfileHelper profileHelper, - ItemHelper itemHelper, - TraderHelper traderHelper, - QuestHelper questHelper, - QuestRewardHelper questRewardHelper, - ProfileFixerService profileFixerService, - SaveServer saveServer, - EventOutputHolder eventOutputHolder, - PlayerScavGenerator playerScavGenerator, - ICloner cloner) - { - _logger = logger; - _timeUtil = timeUtil; - _hashUtil = hashUtil; - _databaseService = databaseService; - _localisationService = localisationService; - _profileHelper = profileHelper; - _itemHelper = itemHelper; - _traderHelper = traderHelper; - _questHelper = questHelper; - _questRewardHelper = questRewardHelper; - _profileFixerService = profileFixerService; - _saveServer = saveServer; - _eventOutputHolder = eventOutputHolder; - _playerScavGenerator = playerScavGenerator; - _cloner = cloner; - } - public string CreateProfile(string sessionId, ProfileCreateRequestData request) { var account = _saveServer.GetProfile(sessionId).ProfileInfo; @@ -146,11 +112,14 @@ public class CreateProfileService // Profile is flagged as wanting quests set to ready to hand in and collect rewards if (profileTemplate.Trader.SetQuestsAvailableForFinish ?? false) { - _questHelper.AddAllQuestsToProfile(profileDetails.CharacterData.PmcData, [ - QuestStatusEnum.AvailableForStart, - QuestStatusEnum.Started, - QuestStatusEnum.AvailableForFinish, - ]); + _questHelper.AddAllQuestsToProfile( + profileDetails.CharacterData.PmcData, + [ + QuestStatusEnum.AvailableForStart, + QuestStatusEnum.Started, + QuestStatusEnum.AvailableForFinish, + ] + ); // Make unused response so applyQuestReward works ItemEventRouterResponse? response = _eventOutputHolder.GetOutput(sessionId); @@ -237,38 +206,46 @@ public class CreateProfileService { if (!pmcData.Inventory.Items.Any((item) => item.Id == pmcData.Inventory.HideoutCustomizationStashId)) { - pmcData.Inventory.Items.Add(new() - { - Id = pmcData.Inventory.HideoutCustomizationStashId, - Template = ItemTpl.HIDEOUTAREACONTAINER_CUSTOMIZATION, - }); + pmcData.Inventory.Items.Add( + new() + { + Id = pmcData.Inventory.HideoutCustomizationStashId, + Template = ItemTpl.HIDEOUTAREACONTAINER_CUSTOMIZATION, + } + ); } if (!pmcData.Inventory.Items.Any((item) => item.Id == pmcData.Inventory.SortingTable)) { - pmcData.Inventory.Items.Add(new() - { - Id = pmcData.Inventory.SortingTable, - Template = ItemTpl.SORTINGTABLE_SORTING_TABLE, - }); + pmcData.Inventory.Items.Add( + new() + { + Id = pmcData.Inventory.SortingTable, + Template = ItemTpl.SORTINGTABLE_SORTING_TABLE, + } + ); } if (!pmcData.Inventory.Items.Any((item) => item.Id == pmcData.Inventory.QuestStashItems)) { - pmcData.Inventory.Items.Add(new() - { - Id = pmcData.Inventory.QuestStashItems, - Template = ItemTpl.STASH_QUESTOFFLINE, - }); + pmcData.Inventory.Items.Add( + new() + { + Id = pmcData.Inventory.QuestStashItems, + Template = ItemTpl.STASH_QUESTOFFLINE, + } + ); } if (!pmcData.Inventory.Items.Any((item) => item.Id == pmcData.Inventory.QuestRaidItems)) { - pmcData.Inventory.Items.Add(new() - { - Id = pmcData.Inventory.QuestRaidItems, - Template = ItemTpl.STASH_QUESTRAID, - }); + pmcData.Inventory.Items.Add( + new() + { + Id = pmcData.Inventory.QuestRaidItems, + Template = ItemTpl.STASH_QUESTRAID, + } + ); } } @@ -290,58 +267,82 @@ public class CreateProfileService { case GameEditions.EDGE_OF_DARKNESS: // Gets EoD tags - fullProfile.CustomisationUnlocks.Add( new CustomisationStorage { - Id = "6746fd09bafff85008048838", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "6746fd09bafff85008048838", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "67471938bafff850080488b7", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "67471938bafff850080488b7", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); break; case GameEditions.UNHEARD: // Gets EoD+Unheard tags - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "6746fd09bafff85008048838", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "6746fd09bafff85008048838", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "67471938bafff850080488b7", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "67471938bafff850080488b7", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "67471928d17d6431550563b5", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "67471928d17d6431550563b5", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "6747193f170146228c0d2226", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "6747193f170146228c0d2226", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); // Unheard Clothing (Cultist Hood) - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "666841a02537107dc508b704", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.SUITE, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "666841a02537107dc508b704", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.SUITE, + } + ); // Unheard background - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "675850ba33627edb710b0592", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.ENVIRONMENT, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "675850ba33627edb710b0592", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.ENVIRONMENT, + } + ); break; } @@ -351,20 +352,26 @@ public class CreateProfileService { if (pretigeLevel >= 1) { - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "674dbf593bee1152d407f005", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "674dbf593bee1152d407f005", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); } if (pretigeLevel >= 2) { - fullProfile.CustomisationUnlocks.Add(new CustomisationStorage { - Id = "675dcfea7ae1a8792107ca99", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.DOG_TAG, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "675dcfea7ae1a8792107ca99", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.DOG_TAG, + } + ); } } @@ -372,11 +379,14 @@ public class CreateProfileService if (fullProfile.ProfileInfo.Edition.ToLower().Contains("developer")) { // CyberTark background - fullProfile.CustomisationUnlocks.Add( new CustomisationStorage{ - Id = "67585108def253bd97084552", - Source = CustomisationSource.DEFAULT, - Type = CustomisationType.ENVIRONMENT, - }); + fullProfile.CustomisationUnlocks.Add( + new CustomisationStorage + { + Id = "67585108def253bd97084552", + Source = CustomisationSource.DEFAULT, + Type = CustomisationType.ENVIRONMENT, + } + ); } } diff --git a/Core/Services/DatabaseService.cs b/Core/Services/DatabaseService.cs index 1dc68099..69dac46e 100644 --- a/Core/Services/DatabaseService.cs +++ b/Core/Services/DatabaseService.cs @@ -10,35 +10,20 @@ using Core.Models.Utils; using Core.Servers; using Core.Utils; using Hideout = Core.Models.Spt.Hideout.Hideout; - using Locations = Core.Models.Spt.Server.Locations; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class DatabaseService +public class DatabaseService( + ISptLogger _logger, + DatabaseServer _databaseServer, + LocalisationService _localisationService, + HashUtil _hashUtil +) { - protected LocationConfig locationConfig; protected bool isDataValid; - - protected ISptLogger _logger; - protected DatabaseServer _databaseServer; - protected LocalisationService _localisationService; - protected HashUtil _hashUtil; - - public DatabaseService( - ISptLogger logger, - DatabaseServer databaseServer, - LocalisationService localisationService, - HashUtil hashUtil - ) - { - _logger = logger; - _databaseServer = databaseServer; - _localisationService = localisationService; - _hashUtil = hashUtil; - } - + /** * @returns assets/database/ */ @@ -64,8 +49,12 @@ public class DatabaseService public Globals GetGlobals() { if (_databaseServer.GetTables().Globals == null) - throw new Exception(_localisationService.GetText("database-data_at_path_missing", - "assets/database/globals.json")); + throw new Exception( + _localisationService.GetText( + "database-data_at_path_missing", + "assets/database/globals.json" + ) + ); return _databaseServer.GetTables().Globals!; } @@ -77,7 +66,8 @@ public class DatabaseService { if (_databaseServer.GetTables().Hideout == null) throw new Exception( - _localisationService.GetText("database-data_at_path_missing", "assets/database/hideout")); + _localisationService.GetText("database-data_at_path_missing", "assets/database/hideout") + ); return _databaseServer.GetTables().Hideout!; } @@ -89,7 +79,8 @@ public class DatabaseService { if (_databaseServer.GetTables().Locales == null) throw new Exception( - _localisationService.GetText("database-data_at_path_missing", "assets/database/locales")); + _localisationService.GetText("database-data_at_path_missing", "assets/database/locales") + ); return _databaseServer.GetTables().Locales!; } @@ -101,7 +92,8 @@ public class DatabaseService { if (_databaseServer.GetTables().Locations == null) throw new Exception( - _localisationService.GetText("database-data_at_path_missing", "assets/database/locales")); + _localisationService.GetText("database-data_at_path_missing", "assets/database/locales") + ); return _databaseServer.GetTables().Locations!; } @@ -127,7 +119,8 @@ public class DatabaseService { if (_databaseServer.GetTables().Match == null) throw new Exception( - _localisationService.GetText("database-data_at_path_missing", "assets/database/locales")); + _localisationService.GetText("database-data_at_path_missing", "assets/database/locales") + ); return _databaseServer.GetTables().Match!; } @@ -138,8 +131,12 @@ public class DatabaseService public ServerBase GetServer() { if (_databaseServer.GetTables().Server == null) - throw new Exception(_localisationService.GetText("database-data_at_path_missing", - "assets/database/server.json")); + throw new Exception( + _localisationService.GetText( + "database-data_at_path_missing", + "assets/database/server.json" + ) + ); return _databaseServer.GetTables().Server!; } @@ -150,8 +147,12 @@ public class DatabaseService public SettingsBase GetSettings() { if (_databaseServer.GetTables().Settings == null) - throw new Exception(_localisationService.GetText("database-data_at_path_missing", - "assets/database/settings.json")); + throw new Exception( + _localisationService.GetText( + "database-data_at_path_missing", + "assets/database/settings.json" + ) + ); return _databaseServer.GetTables().Settings!; } @@ -162,8 +163,12 @@ public class DatabaseService public Templates GetTemplates() { if (_databaseServer.GetTables().Templates == null) - throw new Exception(_localisationService.GetText("database-data_at_path_missing", - "assets/database/templates")); + throw new Exception( + _localisationService.GetText( + "database-data_at_path_missing", + "assets/database/templates" + ) + ); return _databaseServer.GetTables().Templates!; } @@ -174,8 +179,12 @@ public class DatabaseService public List GetAchievements() { if (_databaseServer.GetTables().Templates?.Achievements == null) - throw new Exception(_localisationService.GetText("database-data_at_path_missing", - "assets/database/templates/achievements.json")); + throw new Exception( + _localisationService.GetText( + "database-data_at_path_missing", + "assets/database/templates/achievements.json" + ) + ); return _databaseServer.GetTables().Templates?.Achievements!; } @@ -186,8 +195,12 @@ public class DatabaseService public Dictionary GetCustomization() { if (_databaseServer.GetTables().Templates?.Customization == null) - throw new Exception(_localisationService.GetText("database-data_at_path_missing", - "assets/database/templates/customization.json")); + throw new Exception( + _localisationService.GetText( + "database-data_at_path_missing", + "assets/database/templates/customization.json" + ) + ); return _databaseServer.GetTables().Templates?.Customization!; } diff --git a/Core/Services/FenceService.cs b/Core/Services/FenceService.cs index 06aedd9e..7730ad11 100644 --- a/Core/Services/FenceService.cs +++ b/Core/Services/FenceService.cs @@ -7,16 +7,10 @@ using Core.Models.Spt.Fence; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class FenceService +public class FenceService( + DatabaseService _databaseService +) { - protected DatabaseService _databaseService; - - public FenceService( - DatabaseService databaseService) - { - _databaseService = databaseService; - } - /// /// Replace main fence assort with new assort /// @@ -515,7 +509,7 @@ public class FenceService var minLevel = fenceLevels.Min(); var maxLevel = fenceLevels.Max(); var pmcFenceLevel = Math.Floor(pmcFenceInfo.Standing.Value); - + if (pmcFenceLevel < int.Parse(minLevel)) { return fenceSettings.Levels[minLevel]; diff --git a/Core/Services/GiftService.cs b/Core/Services/GiftService.cs index ea41672c..c924ff09 100644 --- a/Core/Services/GiftService.cs +++ b/Core/Services/GiftService.cs @@ -10,40 +10,16 @@ using Core.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class GiftService +public class GiftService( + ISptLogger _logger, + MailSendService _mailSendService, + LocalisationService _localisationService, + HashUtil _hashUtil, + TimeUtil _timeUtil, + ProfileHelper _profileHelper, + ConfigServer _configServer) { - protected ISptLogger _logger; - - protected MailSendService _mailSendService; - protected LocalisationService _localisationService; - protected HashUtil _hashUtil; - protected TimeUtil _timeUtil; - protected ProfileHelper _profileHelper; - protected ConfigServer _configServer; - - protected GiftsConfig _giftConfig; - - public GiftService - ( - ISptLogger logger, - MailSendService mailSendService, - LocalisationService localisationService, - HashUtil hashUtil, - TimeUtil timeUtil, - ProfileHelper profileHelper, - ConfigServer configServer - ) - { - _logger = logger; - _mailSendService = mailSendService; - _localisationService = localisationService; - _hashUtil = hashUtil; - _timeUtil = timeUtil; - _profileHelper = profileHelper; - _configServer = configServer; - - _giftConfig = _configServer.GetConfig(); - } + protected GiftsConfig _giftConfig = _configServer.GetConfig(); /** * Does a gift with a specific ID exist in db @@ -119,7 +95,8 @@ public class GiftService giftData.LocaleTextId, giftData.Items, giftData.ProfileChangeEvents, - _timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1)); + _timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1) + ); } else { @@ -128,7 +105,8 @@ public class GiftService giftData.MessageText, giftData.Items, _timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1), - giftData.ProfileChangeEvents); + giftData.ProfileChangeEvents + ); } } // Handle user messages @@ -139,7 +117,8 @@ public class GiftService giftData.SenderDetails, giftData.MessageText, giftData.Items, - _timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1)); + _timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1) + ); } else if (giftData.Sender == GiftSenderType.Trader) { @@ -174,10 +153,11 @@ public class GiftService { // TODO: further split out into different message systems like above SYSTEM method // Trader / ragfair - SendMessageDetails details = new () { + SendMessageDetails details = new() + { RecipientId = playerId, Sender = GetMessageType(giftData), - SenderDetails = new () + SenderDetails = new() { Id = GetSenderId(giftData), Aid = 1234567, // TODO - pass proper aid value @@ -188,13 +168,14 @@ public class GiftService ItemsMaxStorageLifetimeSeconds = _timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 0), }; - if (giftData.Trader is not null) { + if (giftData.Trader is not null) + { details.Trader = giftData.Trader; } _mailSendService.SendMessageToPlayer(details); } - + _profileHelper.FlagGiftReceivedInProfile(playerId, giftId, maxGiftsToSendCount); return GiftSentResult.SUCCESS; diff --git a/Core/Services/I18nService.cs b/Core/Services/I18nService.cs index 5fae4b8d..88b2ee5e 100644 --- a/Core/Services/I18nService.cs +++ b/Core/Services/I18nService.cs @@ -14,7 +14,7 @@ public class I18nService private string _setLocale; private Dictionary> _loadedLocales = new(); - + // TODO: try convert to primary ctor public I18nService( FileUtil fileUtil, JsonUtil jsonUtil, diff --git a/Core/Services/ItemBaseClassService.cs b/Core/Services/ItemBaseClassService.cs index 11076cb2..4cd15c90 100644 --- a/Core/Services/ItemBaseClassService.cs +++ b/Core/Services/ItemBaseClassService.cs @@ -5,25 +5,15 @@ using Core.Models.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class ItemBaseClassService +public class ItemBaseClassService( + ISptLogger _logger, + DatabaseService _databaseService, + LocalisationService _localisationService +) { - private readonly ISptLogger _logger; - private readonly DatabaseService _databaseService; - private readonly LocalisationService _localisationService; - private bool _cacheGenerated; private Dictionary> _itemBaseClassesCache; - public ItemBaseClassService( - ISptLogger logger, - DatabaseService databaseService, - LocalisationService localisationService) - { - _logger = logger; - _databaseService = databaseService; - _localisationService = localisationService; - } - /** * Create cache and store inside ItemBaseClassService * Store a dict of an items tpl to the base classes it and its parents have @@ -35,7 +25,8 @@ public class ItemBaseClassService var items = _databaseService.GetItems(); var filteredDbItems = (items).Where((x) => x.Value.Type == "Item"); - foreach (var item in filteredDbItems) { + foreach (var item in filteredDbItems) + { var itemIdToUpdate = item.Value.Id; if (!_itemBaseClassesCache.ContainsKey(item.Value.Id)) { diff --git a/Core/Services/ItemFilterService.cs b/Core/Services/ItemFilterService.cs index 0e48530e..8c2dcab0 100644 --- a/Core/Services/ItemFilterService.cs +++ b/Core/Services/ItemFilterService.cs @@ -8,30 +8,15 @@ using Core.Utils.Cloners; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class ItemFilterService +public class ItemFilterService( + ISptLogger _logger, + ICloner _cloner, + DatabaseServer _databaseServer, + ConfigServer _configServer +) { - protected ISptLogger _logger; - protected ICloner _cloner; - protected DatabaseServer _databaseServer; - protected ConfigServer _configServer; - protected HashSet _lootableItemBlacklistCache = []; - protected ItemConfig _itemConfig; - - public ItemFilterService( - ISptLogger logger, - ICloner cloner, - DatabaseServer databaseServer, - ConfigServer configServer - ) - { - _logger = logger; - _cloner = cloner; - _databaseServer = databaseServer; - _configServer = configServer; - - _itemConfig = _configServer.GetConfig(); - } + protected ItemConfig _itemConfig = _configServer.GetConfig(); /** * Check if the provided template id is blacklisted in config/item.json/blacklist @@ -122,7 +107,8 @@ public class ItemFilterService { if (_lootableItemBlacklistCache.Count == 0) { - foreach (var item in _itemConfig.LootableItemBlacklist) { + foreach (var item in _itemConfig.LootableItemBlacklist) + { _lootableItemBlacklistCache.Add(item); } } diff --git a/Core/Services/LocaleService.cs b/Core/Services/LocaleService.cs index b102e3ff..9fee95bc 100644 --- a/Core/Services/LocaleService.cs +++ b/Core/Services/LocaleService.cs @@ -7,20 +7,16 @@ using Core.Servers; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class LocaleService +public class LocaleService( + ISptLogger _logger, + DatabaseServer _databaseServer, + ConfigServer _configServer +) { - protected LocaleConfig _localeConfig; protected ISptLogger _logger; protected DatabaseServer _databaseServer; protected ConfigServer _configServer; - - public LocaleService(ISptLogger logger, DatabaseServer databaseServer, ConfigServer configServer) - { - _logger = logger; - _databaseServer = databaseServer; - _configServer = configServer; - _localeConfig = configServer.GetConfig(); - } + protected LocaleConfig _localeConfig = _configServer.GetConfig(); /** * Get the eft globals db file based on the configured locale in config/locale.json, if not found, fall back to 'en' @@ -32,7 +28,8 @@ public class LocaleService if (desiredLocale != null) return desiredLocale; _logger.Warning( - $"Unable to find desired locale file using locale: {GetDesiredGameLocale()} from config/locale.json, falling back to 'en'"); + $"Unable to find desired locale file using locale: {GetDesiredGameLocale()} from config/locale.json, falling back to 'en'" + ); return _databaseServer.GetTables().Locales.Global["en"]; } diff --git a/Core/Services/LocalisationService.cs b/Core/Services/LocalisationService.cs index 67cf4935..8449d318 100644 --- a/Core/Services/LocalisationService.cs +++ b/Core/Services/LocalisationService.cs @@ -13,7 +13,7 @@ public class LocalisationService protected DatabaseServer _databaseServer; protected LocaleService _localeService; protected I18nService _i18nService; - + // TODO: turn into primary ctor public LocalisationService( ISptLogger logger, RandomUtil randomUtil, diff --git a/Core/Services/MailSendService.cs b/Core/Services/MailSendService.cs index cf4b6360..707af867 100644 --- a/Core/Services/MailSendService.cs +++ b/Core/Services/MailSendService.cs @@ -11,52 +11,24 @@ using Core.Utils; namespace Core.Services; [Injectable] -public class MailSendService +public class MailSendService( + ISptLogger _logger, + HashUtil _hashUtil, + TimeUtil _timeUtil, + SaveServer _saveServer, + DatabaseService _databaseService, + NotifierHelper _notifierHelper, + DialogueHelper _dialogueHelper, + NotificationSendHelper _notificationSendHelper, + LocalisationService _localisationService, + ItemHelper _itemHelper, + TraderHelper _traderHelper +) { - protected ISptLogger _logger; - protected HashUtil _hashUtil; - protected TimeUtil _timeUtil; - protected SaveServer _saveServer; - protected DatabaseService _databaseService; - protected NotifierHelper _notifierHelper; - protected DialogueHelper _dialogueHelper; - protected NotificationSendHelper _notificationSendHelper; - protected LocalisationService _localisationService; - protected ItemHelper _itemHelper; - protected TraderHelper _traderHelper; - private const string _systemSenderId = "59e7125688a45068a6249071"; protected List _messageTypes = [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE]; protected List _slotNames = ["hideout", "main"]; - public MailSendService - ( - ISptLogger logger, - HashUtil hashUtil, - TimeUtil timeUtil, - SaveServer saveServer, - DatabaseService databaseService, - NotifierHelper notifierHelper, - DialogueHelper dialogueHelper, - NotificationSendHelper notificationSendHelper, - LocalisationService localisationService, - ItemHelper itemHelper, - TraderHelper traderHelper - ) - { - _logger = logger; - _hashUtil = hashUtil; - _timeUtil = timeUtil; - _saveServer = saveServer; - _databaseService = databaseService; - _notifierHelper = notifierHelper; - _dialogueHelper = dialogueHelper; - _notificationSendHelper = notificationSendHelper; - _localisationService = localisationService; - _itemHelper = itemHelper; - _traderHelper = traderHelper; - } - /** * Send a message from an NPC (e.g. prapor) to the player with or without items using direct message text, do not look up any locale * @param sessionId The session ID to send the message to @@ -79,11 +51,16 @@ public class MailSendService { if (trader is null) { - _logger.Error(_localisationService.GetText("mailsend-missing_trader", new - { - messageType = messageType, - sessionId = sessionId, - })); + _logger.Error( + _localisationService.GetText( + "mailsend-missing_trader", + new + { + messageType = messageType, + sessionId = sessionId, + } + ) + ); return; } @@ -95,7 +72,7 @@ public class MailSendService DialogType = MessageType.NPC_TRADER, Trader = trader, MessageText = message, - Items = new () + Items = new() }; // Add items to message @@ -136,11 +113,16 @@ public class MailSendService { if (trader is null) { - _logger.Error(_localisationService.GetText("mailsend-missing_trader", new - { - messageType = messageType, - sessionId = sessionId, - })); + _logger.Error( + _localisationService.GetText( + "mailsend-missing_trader", + new + { + messageType = messageType, + sessionId = sessionId, + } + ) + ); return; } @@ -260,7 +242,7 @@ public class MailSendService Sender = MessageType.USER_MESSAGE, SenderDetails = senderDetails, MessageText = message, - Items = new () + Items = new() }; // add items to message @@ -338,16 +320,18 @@ public class MailSendService return; } - dialogWithNpc.Messages.Add(new() - { - Id = _hashUtil.Generate(), - DateTime = _timeUtil.GetTimeStamp(), - HasRewards = false, - UserId = playerProfile.CharacterData.PmcData.Id, - MessageType = MessageType.USER_MESSAGE, - RewardCollected = false, - Text = message - }); + dialogWithNpc.Messages.Add( + new() + { + Id = _hashUtil.Generate(), + DateTime = _timeUtil.GetTimeStamp(), + HasRewards = false, + UserId = playerProfile.CharacterData.PmcData.Id, + MessageType = MessageType.USER_MESSAGE, + RewardCollected = false, + Text = message + } + ); } private Message CreateDialogMessage(string dialogId, SendMessageDetails messageDetails) @@ -385,10 +369,12 @@ public class MailSendService * @param dialogueId The id of the dialogue (traderId or profileId) * @returns A new instance with data from the found message, otherwise undefined */ - protected ReplyTo? GetMessageToReplyTo(string recipientId, string replyToId, string dialogueId) { + protected ReplyTo? GetMessageToReplyTo(string recipientId, string replyToId, string dialogueId) + { var currentDialogue = _dialogueHelper.GetDialogueFromProfile(recipientId, dialogueId); - if (currentDialogue is null) { + if (currentDialogue is null) + { _logger.Warning($"Unable to find dialogue: {dialogueId} from sender"); return null; } @@ -437,11 +423,14 @@ public class MailSendService var parentItem = GetBaseItemFromRewards(messageDetails.Items); if (parentItem is null) { - _localisationService.GetText("mailsend-missing_parent", new - { - traderId = messageDetails.Trader, - sender = messageDetails.Sender, - }); + _localisationService.GetText( + "mailsend-missing_parent", + new + { + traderId = messageDetails.Trader, + sender = messageDetails.Sender, + } + ); return itemsToSendToPlayer; } @@ -465,11 +454,16 @@ public class MailSendService var itemTemplate = items[reward.Template]; if (itemTemplate is null) { - _logger.Error(_localisationService.GetText("dialog-missing_item_template", new - { - tpl = reward.Template, - type = dialogType, - })); + _logger.Error( + _localisationService.GetText( + "dialog-missing_item_template", + new + { + tpl = reward.Template, + type = dialogType, + } + ) + ); continue; } @@ -558,7 +552,7 @@ public class MailSendService var senderId = GetMessageSenderIdByType(messageDetails); if (senderId is null) throw new Exception(_localisationService.GetText("mail-unable_to_find_message_sender_by_id", messageDetails.Sender)); - + // Does dialog exist var senderDialog = dialogsInProfile.FirstOrDefault(x => x.Key == senderId).Value; if (senderDialog is null) @@ -573,10 +567,10 @@ public class MailSendService New = 0, AttachmentsNew = 0 }; - + senderDialog = dialogsInProfile[senderId]; } - + return senderDialog; } @@ -595,13 +589,13 @@ public class MailSendService if (messageDetails.Sender == MessageType.USER_MESSAGE) return messageDetails.SenderDetails?.Id; - + if (messageDetails.SenderDetails?.Id is not null) return messageDetails.SenderDetails.Id; - + if (messageDetails.Trader is not null) return _traderHelper.GetValidTraderIdByEnumValue(messageDetails.Trader); - + _logger.Warning($"Unable to handle message of type: {messageDetails.Sender}"); return null; } diff --git a/Core/Services/MapMarkerService.cs b/Core/Services/MapMarkerService.cs index de3b400e..87b95f25 100644 --- a/Core/Services/MapMarkerService.cs +++ b/Core/Services/MapMarkerService.cs @@ -8,18 +8,10 @@ using Core.Models.Utils; namespace Core.Services; [Injectable] -public class MapMarkerService +public class MapMarkerService( + ISptLogger _logger +) { - protected ISptLogger _logger; - - public MapMarkerService - ( - ISptLogger logger - ) - { - _logger = logger; - } - /// /// Add note to a map item in player inventory /// @@ -30,10 +22,10 @@ public class MapMarkerService { // Get map from inventory var mapItem = pmcData?.Inventory?.Items?.FirstOrDefault((i) => i?.Id == request?.Item); - + // add marker to map item mapItem.Upd.Map = mapItem?.Upd?.Map ?? new() { Markers = new() }; - + // Update request note with text, then add to maps upd request.MapMarker.Note = SanitiseMapMarkerText(request.MapMarker.Note); mapItem?.Upd?.Map?.Markers?.Add(request.MapMarker); @@ -53,9 +45,7 @@ public class MapMarkerService var mapItem = pmcData.Inventory.Items.FirstOrDefault((item) => item.Id == request.Item); // remove marker - var markers = mapItem.Upd.Map.Markers.Where((marker) => { - return marker.X != request.X && marker.Y != request.Y; - }).ToList(); + var markers = mapItem.Upd.Map.Markers.Where((marker) => { return marker.X != request.X && marker.Y != request.Y; }).ToList(); mapItem.Upd.Map.Markers = markers; return mapItem; diff --git a/Core/Services/MatchBotDetailsCacheService.cs b/Core/Services/MatchBotDetailsCacheService.cs index d9e59829..68e8961c 100644 --- a/Core/Services/MatchBotDetailsCacheService.cs +++ b/Core/Services/MatchBotDetailsCacheService.cs @@ -2,52 +2,41 @@ using Core.Annotations; using Core.Models.Eft.Common.Tables; using Core.Models.Utils; -namespace Core.Services +namespace Core.Services; + +[Injectable(InjectionType.Singleton)] +public class MatchBotDetailsCacheService( + ISptLogger _logger, + LocalisationService _localisationService +) { - [Injectable(InjectionType.Singleton)] - public class MatchBotDetailsCacheService + protected Dictionary _botDetailsCache = new(); + + public void CacheBot(BotBase botToCache) { - protected ISptLogger _logger; - protected LocalisationService _localisationService; - - protected Dictionary _botDetailsCache; - - public MatchBotDetailsCacheService( - ISptLogger logger, - LocalisationService localisationService) + if (botToCache.Info.Nickname is null) { - _logger = logger; - _localisationService = localisationService; - - _botDetailsCache = new(); + _logger.Warning($"Unable to cache: {botToCache.Info.Settings.Role} bot with id: ${botToCache.Id} as it lacks a nickname"); + return; } - public void CacheBot(BotBase botToCache) - { - if (botToCache.Info.Nickname is null) - { - _logger.Warning($"Unable to cache: { botToCache.Info.Settings.Role} bot with id: ${ botToCache.Id} as it lacks a nickname"); - return; - } + var key = $"{botToCache.Info.Nickname.Trim()}{botToCache.Info.Side}"; + _botDetailsCache.TryAdd(key, botToCache); + } - var key = $"{botToCache.Info.Nickname.Trim()}{botToCache.Info.Side}"; - _botDetailsCache.TryAdd(key, botToCache); + public void ClearCache() + { + _botDetailsCache.Clear(); + } + + public BotBase GetBotByNameAndSide(string botName, string botSide) + { + var botInCache = _botDetailsCache.GetValueOrDefault($"{botName}{botSide}`", null); + if (botInCache is null) + { + _logger.Warning($"Bot not found in match bot cache: {botName.ToLower()} {botSide}"); } - public void ClearCache() - { - _botDetailsCache.Clear(); - } - - public BotBase GetBotByNameAndSide(string botName, string botSide) - { - var botInCache = _botDetailsCache.GetValueOrDefault($"{botName}{botSide}`", null); - if (botInCache is null) - { - _logger.Warning($"Bot not found in match bot cache: {botName.ToLower()} { botSide}"); - } - - return botInCache; - } + return botInCache; } } diff --git a/Core/Services/ProfileActivityService.cs b/Core/Services/ProfileActivityService.cs index f00fb0d0..2fa4a3a7 100644 --- a/Core/Services/ProfileActivityService.cs +++ b/Core/Services/ProfileActivityService.cs @@ -4,16 +4,12 @@ using Core.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class ProfileActivityService +public class ProfileActivityService( + TimeUtil _timeUtil +) { - private TimeUtil _timeUtil; private Dictionary profileActivityTimestamps = new(); - public ProfileActivityService(TimeUtil timeUtil) - { - _timeUtil = timeUtil; - } - /** * Was the requested profile active in the last requested minutes * @param sessionId Profile to check @@ -46,12 +42,12 @@ public class ProfileActivityService var lastActivityTimestamp = activity.Value; if (lastActivityTimestamp == null) continue; - + // Profile was active in last x minutes, add to return list if (currentTimestamp - lastActivityTimestamp < minutes * 60) result.Add(activity.Key); } - + return result; } diff --git a/Core/Services/ProfileFixerService.cs b/Core/Services/ProfileFixerService.cs index f4e98e1b..abeddf8b 100644 --- a/Core/Services/ProfileFixerService.cs +++ b/Core/Services/ProfileFixerService.cs @@ -19,49 +19,21 @@ using System.Security.AccessControl; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class ProfileFixerService +public class ProfileFixerService( + ISptLogger _logger, + HashUtil _hashUtil, + JsonUtil _jsonUtil, + ItemHelper _itemHelper, + QuestRewardHelper _questRewardHelper, + TraderHelper _traderHelper, + HideoutHelper _hideoutHelper, + DatabaseService _databaseService, + LocalisationService _localisationService, + ConfigServer _configServer, + InventoryHelper _inventoryHelper +) { - protected ISptLogger _logger; - protected HashUtil _hashUtil; - protected JsonUtil _jsonUtil; - protected ItemHelper _itemHelper; - protected QuestRewardHelper _questRewardHelper; - protected TraderHelper _traderHelper; - protected HideoutHelper _hideoutHelper; - protected DatabaseService _databaseService; - protected LocalisationService _localisationService; - protected ConfigServer _configServer; - protected CoreConfig _coreConfig; - protected InventoryHelper _inventoryHelper; - - public ProfileFixerService( - ISptLogger logger, - HashUtil hashUtil, - JsonUtil jsonUtil, - ItemHelper itemHelper, - QuestRewardHelper questRewardHelper, - TraderHelper traderHelper, - HideoutHelper hideoutHelper, - DatabaseService databaseService, - LocalisationService localisationService, - ConfigServer configServer, - InventoryHelper inventoryHelper - ) - { - _logger = logger; - _hashUtil = hashUtil; - _jsonUtil = jsonUtil; - _itemHelper = itemHelper; - _questRewardHelper = questRewardHelper; - _traderHelper = traderHelper; - _hideoutHelper = hideoutHelper; - _databaseService = databaseService; - _localisationService = localisationService; - _configServer = configServer; - _inventoryHelper = inventoryHelper; - - _coreConfig = _configServer.GetConfig(); - } + protected CoreConfig _coreConfig = _configServer.GetConfig(); /// /// Find issues in the pmc profile data that may cause issues and fix them @@ -365,7 +337,8 @@ public class ProfileFixerService if (profileQuest.Status is QuestStatusEnum.Started or QuestStatusEnum.Success) { var productionRewards = quest.Rewards.Started?.Where( - (reward) => reward.Type == RewardType.ProductionScheme); + (reward) => reward.Type == RewardType.ProductionScheme + ); if (productionRewards is not null) { @@ -380,7 +353,8 @@ public class ProfileFixerService if (profileQuest.Status is QuestStatusEnum.Success) { var productionRewards = quest.Rewards.Success?.Where( - (reward) => reward.Type == RewardType.ProductionScheme); + (reward) => reward.Type == RewardType.ProductionScheme + ); if (productionRewards is not null) { @@ -408,11 +382,16 @@ public class ProfileFixerService 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; } @@ -638,7 +617,9 @@ public class ProfileFixerService _logger.Error(_localisationService.GetText("fixer-trader_found", activeQuest.TraderId)); if (_coreConfig.Fixes.RemoveModItemsFromProfile) { - _logger.Warning($"Non-default quest: {activeQuest.Id} from trader: {activeQuest.TraderId} removed from RepeatableQuests list in profile"); + _logger.Warning( + $"Non-default quest: {activeQuest.Id} from trader: {activeQuest.TraderId} removed from RepeatableQuests list in profile" + ); repeatable.ActiveQuests.Remove(activeQuest); } @@ -653,7 +634,9 @@ public class ProfileFixerService { if (itemsDb[item.Template] is null) { - _logger.Warning($"Non-default quest: {activeQuest.Id} from trader: {activeQuest.TraderId} removed from RepeatableQuests list in profile"); + _logger.Warning( + $"Non-default quest: {activeQuest.Id} from trader: {activeQuest.TraderId} removed from RepeatableQuests list in profile" + ); repeatable.ActiveQuests.Remove(activeQuest); } } diff --git a/Core/Services/RagfairPriceService.cs b/Core/Services/RagfairPriceService.cs index c151230a..8871419a 100644 --- a/Core/Services/RagfairPriceService.cs +++ b/Core/Services/RagfairPriceService.cs @@ -10,24 +10,14 @@ using Core.Models.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class RagfairPriceService +public class RagfairPriceService( + ISptLogger _logger, + HandbookHelper _handbookHelper, + DatabaseService _databaseService +) { - private readonly ISptLogger _logger; - private readonly HandbookHelper _handbookHelper; - private readonly DatabaseService _databaseService; - - protected RagfairServerPrices _prices = new RagfairServerPrices{ StaticPrices = new Dictionary(), DynamicPrices = new Dictionary() }; - -public RagfairPriceService( - ISptLogger logger, - HandbookHelper handbookHelper, - DatabaseService databaseService) - { - _logger = logger; - _handbookHelper = handbookHelper; - _databaseService = databaseService; - } - + protected RagfairServerPrices _prices = new RagfairServerPrices + { StaticPrices = new Dictionary(), DynamicPrices = new Dictionary() }; /// /// Generate static (handbook) and dynamic (prices.json) flea prices, store inside class as dictionaries diff --git a/Core/Services/RaidWeatherService.cs b/Core/Services/RaidWeatherService.cs index 41fb4f55..a6af9717 100644 --- a/Core/Services/RaidWeatherService.cs +++ b/Core/Services/RaidWeatherService.cs @@ -11,40 +11,19 @@ using Core.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class RaidWeatherService +public class RaidWeatherService( + ISptLogger _logger, + DatabaseService _databaseService, + TimeUtil _timeUtil, + WeatherGenerator _weatherGenerator, + SeasonalEventService _seasonalEventService, + WeightedRandomHelper _weightedRandomHelper, + ConfigServer _configServer +) { - protected ISptLogger _logger; - protected DatabaseService _databaseService; - protected TimeUtil _timeUtil; - protected WeatherGenerator _weatherGenerator; - protected SeasonalEventService _seasonalEventService; - protected WeightedRandomHelper _weightedRandomHelper; - protected ConfigServer _configServer; - + protected WeatherConfig _weatherConfig = _configServer.GetConfig(); protected List _weatherForecast = []; - protected WeatherConfig _weatherConfig; - - public RaidWeatherService( - ISptLogger logger, - DatabaseService databaseService, - TimeUtil timeUtil, - WeatherGenerator weatherGenerator, - SeasonalEventService seasonalEventService, - WeightedRandomHelper weightedRandomHelper, - ConfigServer configServer) - { - _logger = logger; - _databaseService = databaseService; - _timeUtil = timeUtil; - _weatherGenerator = weatherGenerator; - _seasonalEventService = seasonalEventService; - _weightedRandomHelper = weightedRandomHelper; - _configServer = configServer; - - _weatherConfig = _configServer.GetConfig(); - } - /// /// Generate 24 hours of weather data starting from midnight today /// @@ -54,7 +33,8 @@ public class RaidWeatherService var staringTimestampMs = _timeUtil.GetTodayMidnightTimeStamp(); // How far into future do we generate weather - var futureTimestampToReachMs = staringTimestampMs + _timeUtil.GetHoursAsSeconds(_weatherConfig.Weather.GenerateWeatherAmountHours ?? 1) * 1000; // Convert to milliseconds + var futureTimestampToReachMs = + staringTimestampMs + _timeUtil.GetHoursAsSeconds(_weatherConfig.Weather.GenerateWeatherAmountHours ?? 1) * 1000; // Convert to milliseconds // Keep adding new weather until we have reached desired future date var nextTimestampMs = staringTimestampMs; @@ -77,8 +57,10 @@ public class RaidWeatherService protected long GetWeightedWeatherTimePeriodMs() { var chosenTimePeriodMinutes = _weightedRandomHelper.WeightedRandom( - _weatherConfig.Weather.TimePeriod.Values, - _weatherConfig.Weather.TimePeriod.Weights).Item; + _weatherConfig.Weather.TimePeriod.Values, + _weatherConfig.Weather.TimePeriod.Weights + ) + .Item; return chosenTimePeriodMinutes * 60 * 1000; // Convert to milliseconds } @@ -119,6 +101,5 @@ public class RaidWeatherService { GenerateWeather(currentSeason); } - } } diff --git a/Core/Services/SeasonalEventService.cs b/Core/Services/SeasonalEventService.cs index ac9f9bc2..b3d5fe29 100644 --- a/Core/Services/SeasonalEventService.cs +++ b/Core/Services/SeasonalEventService.cs @@ -10,29 +10,25 @@ using Core.Servers; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class SeasonalEventService +public class SeasonalEventService( + ISptLogger _logger, + DatabaseService _databaseService, + GiftService _giftService, + LocalisationService _localisationService, + BotHelper _botHelper, + ProfileHelper _profileHelper, + ConfigServer _configServer +) { - protected ISptLogger _logger; - - protected DatabaseService _databaseService; - - //protected DatabaseImporter _databaseImporter; - protected GiftService _giftService; - protected LocalisationService _localisationService; - protected BotHelper _botHelper; - protected ProfileHelper _profileHelper; - protected ConfigServer _configServer; - - private bool _christmasEventActive = false; - private bool _halloweenEventActive = false; - - protected SeasonalEventConfig _seasonalEventConfig; - protected QuestConfig _questConfig; - protected HttpConfig _httpConfig; - protected WeatherConfig _weatherConfig; - protected LocationConfig _locationConfig; + protected SeasonalEventConfig _seasonalEventConfig = _configServer.GetConfig(); + protected QuestConfig _questConfig = _configServer.GetConfig(); + protected HttpConfig _httpConfig = _configServer.GetConfig(); + protected WeatherConfig _weatherConfig = _configServer.GetConfig(); + protected LocationConfig _locationConfig = _configServer.GetConfig(); private List _currentlyActiveEvents = []; + private bool _christmasEventActive = false; + private bool _halloweenEventActive = false; protected IReadOnlyList _christmasEventItems = [ @@ -63,34 +59,6 @@ public class SeasonalEventService ItemTpl.FACECOVER_HOCKEY_PLAYER_MASK_QUIET ]; - public SeasonalEventService - ( - ISptLogger logger, - DatabaseService databaseService, - //DatabaseImporter databaseImporter, - GiftService giftService, - LocalisationService localisationService, - BotHelper botHelper, - ProfileHelper profileHelper, - ConfigServer configServer - ) - { - _logger = logger; - _databaseService = databaseService; - //_databaseImporter = databaseImporter; - _giftService = giftService; - _localisationService = localisationService; - _botHelper = botHelper; - _profileHelper = profileHelper; - _configServer = configServer; - - _seasonalEventConfig = _configServer.GetConfig(); - _questConfig = _configServer.GetConfig(); - _httpConfig = _configServer.GetConfig(); - _weatherConfig = _configServer.GetConfig(); - _locationConfig = _configServer.GetConfig(); - } - /// /// Get an array of christmas items found in bots inventories as loot /// @@ -372,11 +340,14 @@ public class SeasonalEventService if (botInventory.Equipment[equipmentSlotKey] is null) { _logger.Warning( - _localisationService.GetText("seasonal-missing_equipment_slot_on_bot", new - { - equipmentSlot = equipmentSlotKey, - botRole = botRole, - }) + _localisationService.GetText( + "seasonal-missing_equipment_slot_on_bot", + new + { + equipmentSlot = equipmentSlotKey, + botRole = botRole, + } + ) ); } @@ -393,11 +364,14 @@ public class SeasonalEventService if (prop is null) { _logger.Warning( - _localisationService.GetText("seasonal-missing_loot_container_slot_on_bot", new - { - lootContainer = lootContainerKey, - botRole = botRole, - }) + _localisationService.GetText( + "seasonal-missing_loot_container_slot_on_bot", + new + { + lootContainer = lootContainerKey, + botRole = botRole, + } + ) ); } @@ -779,9 +753,11 @@ public class SeasonalEventService /// protected void AddPumpkinsToScavBackpacks() { - _databaseService.GetBots().Types["assault"].BotInventory.Items.Backpack[ - ItemTpl.RANDOMLOOTCONTAINER_PUMPKIN_RAND_LOOT_CONTAINER - ] = 400; + _databaseService.GetBots() + .Types["assault"] + .BotInventory.Items.Backpack[ + ItemTpl.RANDOMLOOTCONTAINER_PUMPKIN_RAND_LOOT_CONTAINER + ] = 400; } protected void RenameBitcoin() diff --git a/Core/Services/TraderPurchasePersisterService.cs b/Core/Services/TraderPurchasePersisterService.cs index f33d4866..09d1e11a 100644 --- a/Core/Services/TraderPurchasePersisterService.cs +++ b/Core/Services/TraderPurchasePersisterService.cs @@ -10,34 +10,16 @@ using Core.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] -public class TraderPurchasePersisterService +public class TraderPurchasePersisterService( + ISptLogger _logger, + RandomUtil _randomUtil, + TimeUtil _timeUtil, + ProfileHelper _profileHelper, + LocalisationService _localisationService, + ConfigServer _configServer +) { - protected ISptLogger _logger; - protected RandomUtil _randomUtil; - protected TimeUtil _timeUtil; - protected ProfileHelper _profileHelper; - protected LocalisationService _localisationService; - protected ConfigServer _configServer; - - protected TraderConfig _traderConfig; - - public TraderPurchasePersisterService( - ISptLogger logger, - RandomUtil randomUtil, - TimeUtil timeUtil, - ProfileHelper profileHelper, - LocalisationService localisationService, - ConfigServer configServer) - { - _logger = logger; - _randomUtil = randomUtil; - _timeUtil = timeUtil; - _profileHelper = profileHelper; - _localisationService = localisationService; - _configServer = configServer; - - _traderConfig = _configServer.GetConfig(); - } + protected TraderConfig _traderConfig = _configServer.GetConfig(); /** * Get the purchases made from a trader for this profile before the last trader reset @@ -83,7 +65,8 @@ public class TraderPurchasePersisterService public void RemoveStalePurchasesFromProfiles(string traderId) { var profiles = _profileHelper.GetProfiles(); - foreach (var profileKvP in profiles) { + foreach (var profileKvP in profiles) + { var profile = profileKvP.Value; // Skip if no purchases or no trader-specific purchases @@ -93,15 +76,20 @@ public class TraderPurchasePersisterService continue; } - foreach (var purchaseKvP in purchasesFromTrader) { + foreach (var purchaseKvP in purchasesFromTrader) + { var traderUpdateDetails = _traderConfig.UpdateTime.FirstOrDefault((x) => x.TraderId == traderId); if (traderUpdateDetails is null) { _logger.Error( - _localisationService.GetText("trader-unable_to_delete_stale_purchases", new { - profileId = profile.ProfileInfo.ProfileId, - traderId = traderId, - }) + _localisationService.GetText( + "trader-unable_to_delete_stale_purchases", + new + { + profileId = profile.ProfileInfo.ProfileId, + traderId = traderId, + } + ) ); continue; @@ -109,12 +97,12 @@ public class TraderPurchasePersisterService var purchaseDetails = purchaseKvP.Value; var resetTimeForItem = - purchaseDetails.PurchaseTimestamp + + purchaseDetails.PurchaseTimestamp + _randomUtil.GetInt((int)traderUpdateDetails.Seconds.Min, (int)traderUpdateDetails.Seconds.Max); if (resetTimeForItem < _timeUtil.GetTimeStamp()) { // Item was purchased far enough in past a trader refresh would have occured, remove purchase record from profile - _logger.Debug($"Removed trader: { traderId} purchase: { purchaseKvP} from profile: { profile.ProfileInfo.ProfileId}"); + _logger.Debug($"Removed trader: {traderId} purchase: {purchaseKvP} from profile: {profile.ProfileInfo.ProfileId}"); profile.TraderPurchases.Remove(purchaseKvP.Key); }