primary ctor for services, servers, loaders

This commit is contained in:
CWX
2025-01-18 20:32:59 +00:00
parent 3402f94398
commit 077f86ac46
28 changed files with 590 additions and 843 deletions
+5 -14
View File
@@ -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<PostDBModLoader> _logger,
IEnumerable<IPostDBLoadMod> _postDbLoadMods
) : OnLoad
{
protected ISptLogger<PostDBModLoader> _logger;
protected IEnumerable<IPostDBLoadMod> _postDbLoadMods;
public PostDBModLoader(
ISptLogger<PostDBModLoader> logger,
IEnumerable<IPostDBLoadMod> 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...");
}
+5 -13
View File
@@ -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<PostSptModLoader> _logger,
IEnumerable<IPostSptLoadMod> _postSptLoadMods
) : OnLoad
{
protected ISptLogger<PostSptModLoader> _logger;
protected IEnumerable<IPostSptLoadMod> _postSptLoadMods;
public PostSptModLoader(
ISptLogger<PostSptModLoader> logger,
IEnumerable<IPostSptLoadMod> 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...");
}
+15 -31
View File
@@ -14,7 +14,15 @@ using Core.Utils;
namespace Core.Servers;
[Injectable(InjectionType.Singleton)]
public class SaveServer
public class SaveServer(
FileUtil _vfs,
IEnumerable<SaveLoadRouter> _saveLoadRouters,
JsonUtil _jsonUtil,
HashUtil _hashUtil,
LocalisationService _localisationService,
ISptLogger<SaveServer> _logger,
ConfigServer _configServer
)
{
protected string profileFilepath = "user/profiles/";
@@ -24,33 +32,6 @@ public class SaveServer
protected readonly Dictionary<string, Func<SptProfile, SptProfile>> onBeforeSaveCallbacks = new();
protected Dictionary<string, string> saveMd5 = new();
protected readonly FileUtil _vfs;
protected readonly IEnumerable<SaveLoadRouter> _saveLoadRouters;
protected readonly JsonUtil _jsonUtil;
protected readonly HashUtil _hashUtil;
protected readonly LocalisationService _localisationService;
protected readonly ISptLogger<SaveServer> _logger;
protected readonly ConfigServer _configServer;
public SaveServer(
FileUtil vfs,
IEnumerable<SaveLoadRouter> saveLoadRouters,
JsonUtil jsonUtil,
HashUtil hashUtil,
LocalisationService localisationService,
ISptLogger<SaveServer> 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));
}
+6 -16
View File
@@ -8,23 +8,12 @@ using Core.Utils;
namespace Core.Servers;
[Injectable(InjectionType.Singleton)]
public class WebSocketServer
public class WebSocketServer(
IEnumerable<IWebSocketConnectionHandler> _webSocketConnectionHandler,
ISptLogger<WebSocketServer> _logger,
JsonUtil _jsonUtil
)
{
protected IEnumerable<IWebSocketConnectionHandler> _webSocketConnectionHandler;
protected ISptLogger<WebSocketServer> _logger;
protected JsonUtil _jsonUtil;
public WebSocketServer(
IEnumerable<IWebSocketConnectionHandler> webSocketConnectionHandlers,
ISptLogger<WebSocketServer> 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;
}
}
@@ -5,17 +5,10 @@ using Core.Annotations;
namespace Core.Servers.Ws.Message;
[Injectable]
public class DefaultSptWebSocketMessageHandler : ISptWebSocketMessageHandler
public class DefaultSptWebSocketMessageHandler(
Models.Utils.ISptLogger<DefaultSptWebSocketMessageHandler> _logger
) : ISptWebSocketMessageHandler
{
protected Models.Utils.ISptLogger<DefaultSptWebSocketMessageHandler> _logger;
public DefaultSptWebSocketMessageHandler(
Models.Utils.ISptLogger<DefaultSptWebSocketMessageHandler> logger
)
{
_logger = logger;
}
public async Task OnSptMessage(string sessionID, WebSocket client, byte[] rawData)
{
_logger.Debug($"[{sessionID}] SPT message received: {Encoding.UTF8.GetString(rawData)}");
@@ -12,39 +12,24 @@ using Core.Utils;
namespace Core.Servers.Ws;
[Injectable(InjectionType.Singleton)]
public class SptWebSocketConnectionHandler : IWebSocketConnectionHandler
public class SptWebSocketConnectionHandler(
ISptLogger<SptWebSocketConnectionHandler> _logger,
LocalisationService _localisationService,
JsonUtil _jsonUtil,
ProfileHelper _profileHelper,
ConfigServer _configServer,
IEnumerable<ISptWebSocketMessageHandler> _messageHandlers
) : IWebSocketConnectionHandler
{
protected HttpConfig _httpConfig = _configServer.GetConfig<HttpConfig>();
protected Dictionary<string, WebSocket> _sockets = new();
protected Dictionary<string, Timer> _socketAliveTimers = new();
protected Dictionary<string, CancellationTokenSource> _receiveTasks = new();
protected object _lockObject = new();
protected ISptLogger<SptWebSocketConnectionHandler> _logger;
protected LocalisationService _localisationService;
protected JsonUtil _jsonUtil;
protected ProfileHelper _profileHelper;
protected HttpConfig _httpConfig;
protected IEnumerable<ISptWebSocketMessageHandler> _messageHandlers;
protected Lock _lockObject = new();
protected WsPing _defaultNotification = new();
public SptWebSocketConnectionHandler(
ISptLogger<SptWebSocketConnectionHandler> logger,
LocalisationService localisationService,
JsonUtil jsonUtil,
ProfileHelper profileHelper,
ConfigServer configServer,
IEnumerable<ISptWebSocketMessageHandler> messageHandlers
)
{
_logger = logger;
_localisationService = localisationService;
_jsonUtil = jsonUtil;
_profileHelper = profileHelper;
_messageHandlers = messageHandlers;
_httpConfig = configServer.GetConfig<HttpConfig>();
}
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(
+8 -13
View File
@@ -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<BotConfig>();
}
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
/// <summary>
/// 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
);
}
/// <summary>
+37 -46
View File
@@ -12,34 +12,17 @@ using Core.Utils.Cloners;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class BotLootCacheService
public class BotLootCacheService(
ISptLogger<BotLootCacheService> _logger,
ItemHelper _itemHelper,
PMCLootGenerator _pmcLootGenerator,
LocalisationService _localisationService,
RagfairPriceService _ragfairPriceService,
ICloner _cloner
)
{
protected ISptLogger<BotLootCacheService> _logger;
protected ItemHelper _itemHelper;
protected PMCLootGenerator _pmcLootGenerator;
protected LocalisationService _localisationService;
protected RagfairPriceService _ragfairPriceService;
protected ICloner _cloner;
protected Dictionary<string, BotLootCache> _lootCache = new();
public BotLootCacheService(
ISptLogger<BotLootCacheService> logger,
ItemHelper itemHelper,
PMCLootGenerator pmcLootGenerator,
LocalisationService localisationService,
RagfairPriceService ragfairPriceService,
ICloner cloner
)
{
_logger = logger;
_itemHelper = itemHelper;
_pmcLootGenerator = pmcLootGenerator;
_localisationService = localisationService;
_ragfairPriceService = ragfairPriceService;
_cloner = cloner;
}
/// <summary>
/// Remove cached bot loot data
/// </summary>
@@ -477,7 +460,8 @@ public class BotLootCacheService
/// <param name="itemsToAdd">items to add to combined pool if unique</param>
protected void AddUniqueItemsToPool(List<TemplateItem> poolToAddTo, List<TemplateItem> itemsToAdd)
{
if (poolToAddTo.Count() == 0) {
if (poolToAddTo.Count() == 0)
{
poolToAddTo.AddRange(itemsToAdd);
return;
}
@@ -488,9 +472,11 @@ public class BotLootCacheService
protected void AddItemsToPool(Dictionary<string, double> poolToAddTo, Dictionary<string, double> 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
/// <param name="botRole">Bot role to hydrate</param>
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;
}
+18 -38
View File
@@ -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<BotNameService> _logger,
BotHelper _botHelper,
RandomUtil _randomUtil,
LocalisationService _localisationService,
DatabaseService _databaseService,
ConfigServer _configServer
)
{
protected ISptLogger<BotNameService> _logger;
protected BotHelper _botHelper;
protected RandomUtil _randomUtil;
protected LocalisationService _localisationService;
protected DatabaseService _databaseService;
protected ConfigServer _configServer;
protected BotConfig _botConfig;
protected HashSet<string> _usedNameCache;
public BotNameService(
ISptLogger<BotNameService> 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<BotConfig>();
_usedNameCache = new HashSet<string>();
}
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
protected HashSet<string> _usedNameCache = new HashSet<string>();
/// <summary>
/// Clear out any entries in Name Set
/// </summary>
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
/// </summary>
/// <param name="bot">Bot to update</param>
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
/// </summary>
/// <returns>PMC name as string</returns>
protected string GetRandomPmcName()
protected string GetRandomPmcName()
{
var bots = _databaseService.GetBots().Types;
+6 -19
View File
@@ -10,26 +10,13 @@ using Core.Servers;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class BotWeaponModLimitService
public class BotWeaponModLimitService(
ISptLogger<BotWeaponModLimitService> _logger,
ConfigServer _configServer,
ItemHelper _itemHelper
)
{
private readonly ISptLogger<BotWeaponModLimitService> _logger;
private readonly ConfigServer _configServer;
private readonly ItemHelper _itemHelper;
private readonly BotConfig _botConfig;
public BotWeaponModLimitService
(
ISptLogger<BotWeaponModLimitService> logger,
ConfigServer configServer,
ItemHelper itemHelper
)
{
_logger = logger;
_configServer = configServer;
_itemHelper = itemHelper;
_botConfig = _configServer.GetConfig<BotConfig>();
}
protected BotConfig _botConfig = _configServer.GetConfig<BotConfig>();
/// <summary>
/// Initalise mod limits to be used when generating a weapon
+141 -131
View File
@@ -16,58 +16,24 @@ using Core.Utils.Cloners;
namespace Core.Services;
[Injectable]
public class CreateProfileService
public class CreateProfileService(
ISptLogger<CreateProfileService> _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<CreateProfileService> _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<CreateProfileService> 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,
}
);
}
}
+51 -38
View File
@@ -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<DatabaseService> _logger,
DatabaseServer _databaseServer,
LocalisationService _localisationService,
HashUtil _hashUtil
)
{
protected LocationConfig locationConfig;
protected bool isDataValid;
protected ISptLogger<DatabaseService> _logger;
protected DatabaseServer _databaseServer;
protected LocalisationService _localisationService;
protected HashUtil _hashUtil;
public DatabaseService(
ISptLogger<DatabaseService> 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<Achievement> 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<string, CustomizationItem> 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!;
}
+4 -10
View File
@@ -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;
}
/// <summary>
/// Replace main fence assort with new assort
/// </summary>
@@ -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];
+21 -40
View File
@@ -10,40 +10,16 @@ using Core.Utils;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class GiftService
public class GiftService(
ISptLogger<GiftService> _logger,
MailSendService _mailSendService,
LocalisationService _localisationService,
HashUtil _hashUtil,
TimeUtil _timeUtil,
ProfileHelper _profileHelper,
ConfigServer _configServer)
{
protected ISptLogger<GiftService> _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<GiftService> 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<GiftsConfig>();
}
protected GiftsConfig _giftConfig = _configServer.GetConfig<GiftsConfig>();
/**
* 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;
+1 -1
View File
@@ -14,7 +14,7 @@ public class I18nService
private string _setLocale;
private Dictionary<string, Dictionary<string, string>> _loadedLocales = new();
// TODO: try convert to primary ctor
public I18nService(
FileUtil fileUtil,
JsonUtil jsonUtil,
+7 -16
View File
@@ -5,25 +5,15 @@ using Core.Models.Utils;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class ItemBaseClassService
public class ItemBaseClassService(
ISptLogger<ItemBaseClassService> _logger,
DatabaseService _databaseService,
LocalisationService _localisationService
)
{
private readonly ISptLogger<ItemBaseClassService> _logger;
private readonly DatabaseService _databaseService;
private readonly LocalisationService _localisationService;
private bool _cacheGenerated;
private Dictionary<string, List<string>> _itemBaseClassesCache;
public ItemBaseClassService(
ISptLogger<ItemBaseClassService> 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))
{
+9 -23
View File
@@ -8,30 +8,15 @@ using Core.Utils.Cloners;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class ItemFilterService
public class ItemFilterService(
ISptLogger<ItemFilterService> _logger,
ICloner _cloner,
DatabaseServer _databaseServer,
ConfigServer _configServer
)
{
protected ISptLogger<ItemFilterService> _logger;
protected ICloner _cloner;
protected DatabaseServer _databaseServer;
protected ConfigServer _configServer;
protected HashSet<string> _lootableItemBlacklistCache = [];
protected ItemConfig _itemConfig;
public ItemFilterService(
ISptLogger<ItemFilterService> logger,
ICloner cloner,
DatabaseServer databaseServer,
ConfigServer configServer
)
{
_logger = logger;
_cloner = cloner;
_databaseServer = databaseServer;
_configServer = configServer;
_itemConfig = _configServer.GetConfig<ItemConfig>();
}
protected ItemConfig _itemConfig = _configServer.GetConfig<ItemConfig>();
/**
* 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);
}
}
+8 -11
View File
@@ -7,20 +7,16 @@ using Core.Servers;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class LocaleService
public class LocaleService(
ISptLogger<LocaleService> _logger,
DatabaseServer _databaseServer,
ConfigServer _configServer
)
{
protected LocaleConfig _localeConfig;
protected ISptLogger<LocaleService> _logger;
protected DatabaseServer _databaseServer;
protected ConfigServer _configServer;
public LocaleService(ISptLogger<LocaleService> logger, DatabaseServer databaseServer, ConfigServer configServer)
{
_logger = logger;
_databaseServer = databaseServer;
_configServer = configServer;
_localeConfig = configServer.GetConfig<LocaleConfig>();
}
protected LocaleConfig _localeConfig = _configServer.GetConfig<LocaleConfig>();
/**
* 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"];
}
+1 -1
View File
@@ -13,7 +13,7 @@ public class LocalisationService
protected DatabaseServer _databaseServer;
protected LocaleService _localeService;
protected I18nService _i18nService;
// TODO: turn into primary ctor
public LocalisationService(
ISptLogger<LocalisationService> logger,
RandomUtil randomUtil,
+75 -81
View File
@@ -11,52 +11,24 @@ using Core.Utils;
namespace Core.Services;
[Injectable]
public class MailSendService
public class MailSendService(
ISptLogger<MailSendService> _logger,
HashUtil _hashUtil,
TimeUtil _timeUtil,
SaveServer _saveServer,
DatabaseService _databaseService,
NotifierHelper _notifierHelper,
DialogueHelper _dialogueHelper,
NotificationSendHelper _notificationSendHelper,
LocalisationService _localisationService,
ItemHelper _itemHelper,
TraderHelper _traderHelper
)
{
protected ISptLogger<MailSendService> _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<MessageType> _messageTypes = [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE];
protected List<string> _slotNames = ["hideout", "main"];
public MailSendService
(
ISptLogger<MailSendService> 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;
}
+6 -16
View File
@@ -8,18 +8,10 @@ using Core.Models.Utils;
namespace Core.Services;
[Injectable]
public class MapMarkerService
public class MapMarkerService(
ISptLogger<MapMarkerService> _logger
)
{
protected ISptLogger<MapMarkerService> _logger;
public MapMarkerService
(
ISptLogger<MapMarkerService> logger
)
{
_logger = logger;
}
/// <summary>
/// Add note to a map item in player inventory
/// </summary>
@@ -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;
+28 -39
View File
@@ -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<MatchBotDetailsCacheService> _logger,
LocalisationService _localisationService
)
{
[Injectable(InjectionType.Singleton)]
public class MatchBotDetailsCacheService
protected Dictionary<string, BotBase> _botDetailsCache = new();
public void CacheBot(BotBase botToCache)
{
protected ISptLogger<MatchBotDetailsCacheService> _logger;
protected LocalisationService _localisationService;
protected Dictionary<string, BotBase> _botDetailsCache;
public MatchBotDetailsCacheService(
ISptLogger<MatchBotDetailsCacheService> 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;
}
}
+5 -9
View File
@@ -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<string, long> 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;
}
+34 -51
View File
@@ -19,49 +19,21 @@ using System.Security.AccessControl;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class ProfileFixerService
public class ProfileFixerService(
ISptLogger<ProfileFixerService> _logger,
HashUtil _hashUtil,
JsonUtil _jsonUtil,
ItemHelper _itemHelper,
QuestRewardHelper _questRewardHelper,
TraderHelper _traderHelper,
HideoutHelper _hideoutHelper,
DatabaseService _databaseService,
LocalisationService _localisationService,
ConfigServer _configServer,
InventoryHelper _inventoryHelper
)
{
protected ISptLogger<ProfileFixerService> _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<ProfileFixerService> 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<CoreConfig>();
}
protected CoreConfig _coreConfig = _configServer.GetConfig<CoreConfig>();
/// <summary>
/// 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);
}
}
+7 -17
View File
@@ -10,24 +10,14 @@ using Core.Models.Utils;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class RagfairPriceService
public class RagfairPriceService(
ISptLogger<RagfairPriceService> _logger,
HandbookHelper _handbookHelper,
DatabaseService _databaseService
)
{
private readonly ISptLogger<RagfairPriceService> _logger;
private readonly HandbookHelper _handbookHelper;
private readonly DatabaseService _databaseService;
protected RagfairServerPrices _prices = new RagfairServerPrices{ StaticPrices = new Dictionary<string, double>(), DynamicPrices = new Dictionary<string, double>() };
public RagfairPriceService(
ISptLogger<RagfairPriceService> logger,
HandbookHelper handbookHelper,
DatabaseService databaseService)
{
_logger = logger;
_handbookHelper = handbookHelper;
_databaseService = databaseService;
}
protected RagfairServerPrices _prices = new RagfairServerPrices
{ StaticPrices = new Dictionary<string, double>(), DynamicPrices = new Dictionary<string, double>() };
/// <summary>
/// Generate static (handbook) and dynamic (prices.json) flea prices, store inside class as dictionaries
+16 -35
View File
@@ -11,40 +11,19 @@ using Core.Utils;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class RaidWeatherService
public class RaidWeatherService(
ISptLogger<RaidWeatherService> _logger,
DatabaseService _databaseService,
TimeUtil _timeUtil,
WeatherGenerator _weatherGenerator,
SeasonalEventService _seasonalEventService,
WeightedRandomHelper _weightedRandomHelper,
ConfigServer _configServer
)
{
protected ISptLogger<RaidWeatherService> _logger;
protected DatabaseService _databaseService;
protected TimeUtil _timeUtil;
protected WeatherGenerator _weatherGenerator;
protected SeasonalEventService _seasonalEventService;
protected WeightedRandomHelper _weightedRandomHelper;
protected ConfigServer _configServer;
protected WeatherConfig _weatherConfig = _configServer.GetConfig<WeatherConfig>();
protected List<Weather> _weatherForecast = [];
protected WeatherConfig _weatherConfig;
public RaidWeatherService(
ISptLogger<RaidWeatherService> 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<WeatherConfig>();
}
/// <summary>
/// Generate 24 hours of weather data starting from midnight today
/// </summary>
@@ -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);
}
}
}
+37 -61
View File
@@ -10,29 +10,25 @@ using Core.Servers;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class SeasonalEventService
public class SeasonalEventService(
ISptLogger<SeasonalEventService> _logger,
DatabaseService _databaseService,
GiftService _giftService,
LocalisationService _localisationService,
BotHelper _botHelper,
ProfileHelper _profileHelper,
ConfigServer _configServer
)
{
protected ISptLogger<SeasonalEventService> _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<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 =
[
@@ -63,34 +59,6 @@ public class SeasonalEventService
ItemTpl.FACECOVER_HOCKEY_PLAYER_MASK_QUIET
];
public SeasonalEventService
(
ISptLogger<SeasonalEventService> 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<SeasonalEventConfig>();
_questConfig = _configServer.GetConfig<QuestConfig>();
_httpConfig = _configServer.GetConfig<HttpConfig>();
_weatherConfig = _configServer.GetConfig<WeatherConfig>();
_locationConfig = _configServer.GetConfig<LocationConfig>();
}
/// <summary>
/// Get an array of christmas items found in bots inventories as loot
/// </summary>
@@ -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
/// </summary>
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()
+23 -35
View File
@@ -10,34 +10,16 @@ using Core.Utils;
namespace Core.Services;
[Injectable(InjectionType.Singleton)]
public class TraderPurchasePersisterService
public class TraderPurchasePersisterService(
ISptLogger<TraderPurchasePersisterService> _logger,
RandomUtil _randomUtil,
TimeUtil _timeUtil,
ProfileHelper _profileHelper,
LocalisationService _localisationService,
ConfigServer _configServer
)
{
protected ISptLogger<TraderPurchasePersisterService> _logger;
protected RandomUtil _randomUtil;
protected TimeUtil _timeUtil;
protected ProfileHelper _profileHelper;
protected LocalisationService _localisationService;
protected ConfigServer _configServer;
protected TraderConfig _traderConfig;
public TraderPurchasePersisterService(
ISptLogger<TraderPurchasePersisterService> 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<TraderConfig>();
}
protected TraderConfig _traderConfig = _configServer.GetConfig<TraderConfig>();
/**
* 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);
}