diff --git a/Core/Callbacks/HideoutCallbacks.cs b/Core/Callbacks/HideoutCallbacks.cs index 80dd2449..c6fa0bda 100644 --- a/Core/Callbacks/HideoutCallbacks.cs +++ b/Core/Callbacks/HideoutCallbacks.cs @@ -14,9 +14,9 @@ namespace Core.Callbacks; [Injectable(InjectableTypeOverride = typeof(OnUpdate), TypePriority = OnUpdateOrder.HideoutCallbacks)] public class HideoutCallbacks : OnUpdate { - private readonly HideoutController _hideoutController; - private readonly ConfigServer _configServer; - private readonly HideoutConfig _hideoutConfig; + protected HideoutController _hideoutController; + protected ConfigServer _configServer; + protected HideoutConfig _hideoutConfig; public HideoutCallbacks ( diff --git a/Core/Callbacks/HttpCallbacks.cs b/Core/Callbacks/HttpCallbacks.cs index d132035f..5f48814e 100644 --- a/Core/Callbacks/HttpCallbacks.cs +++ b/Core/Callbacks/HttpCallbacks.cs @@ -8,8 +8,8 @@ namespace Core.Callbacks; [Injectable(InjectionType.Singleton, InjectableTypeOverride = typeof(OnLoad), TypePriority = OnLoadOrder.HttpCallbacks)] public class HttpCallbacks : OnLoad { - private readonly HttpServer _httpServer; - private readonly ApplicationContext _applicationContext; + protected HttpServer _httpServer; + protected ApplicationContext _applicationContext; public HttpCallbacks(HttpServer httpServer, ApplicationContext applicationContext) { _httpServer = httpServer; diff --git a/Core/Context/ApplicationContext.cs b/Core/Context/ApplicationContext.cs index 23bfb345..4e6d4463 100644 --- a/Core/Context/ApplicationContext.cs +++ b/Core/Context/ApplicationContext.cs @@ -6,8 +6,8 @@ namespace Core.Context; public class ApplicationContext { private const short MaxSavedValues = 10; - private readonly Dictionary> variables = new(); - private readonly object variablesLock = new(); + protected Dictionary> variables = new(); + protected object variablesLock = new(); public ContextVariable? GetLatestValue(ContextVariableType type) { @@ -58,4 +58,4 @@ public class ApplicationContext variables.Remove(type); } } -} \ No newline at end of file +} diff --git a/Core/Context/ContextVariable.cs b/Core/Context/ContextVariable.cs index 7c3b9280..e64ec2f9 100644 --- a/Core/Context/ContextVariable.cs +++ b/Core/Context/ContextVariable.cs @@ -2,9 +2,9 @@ namespace Core.Context; public class ContextVariable { - private readonly object _value; - private readonly ContextVariableType _internalType; - private readonly DateTime _timestamp; + protected object _value; + protected ContextVariableType _internalType; + protected DateTime _timestamp; public ContextVariable(object value, ContextVariableType contextVariableInternalType) { diff --git a/Core/Controllers/AchievementController.cs b/Core/Controllers/AchievementController.cs index 396c2baf..4ad72b36 100644 --- a/Core/Controllers/AchievementController.cs +++ b/Core/Controllers/AchievementController.cs @@ -1,19 +1,19 @@ using Core.Annotations; using Core.Models.Eft.Profile; +using Core.Models.Utils; using Core.Services; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Controllers; [Injectable] public class AchievementController { - protected ILogger _logger; + protected ISptLogger _logger; protected DatabaseService _databaseService; public AchievementController ( - ILogger logger, + ISptLogger logger, DatabaseService databaseService ) { diff --git a/Core/Controllers/BotController.cs b/Core/Controllers/BotController.cs index c72c0227..913205d4 100644 --- a/Core/Controllers/BotController.cs +++ b/Core/Controllers/BotController.cs @@ -7,21 +7,20 @@ using Core.Models.Eft.Bot; using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Match; -using Core.Models.Enums; using Core.Models.Spt.Bots; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Controllers; [Injectable] public class BotController { - protected ILogger _logger; + protected ISptLogger _logger; protected DatabaseService _databaseService; protected BotGenerator _botGenerator; @@ -32,7 +31,7 @@ public class BotController protected MatchBotDeatilsCacheService _matchBotDeatilsCacheService; protected LocalisationService _localisationService; protected SeasonalEventService _seasonalEventService; - private readonly MatchBotDetailsCacheService _matchBotDetailsCacheService; + protected MatchBotDetailsCacheService _matchBotDetailsCacheService; protected ProfileHelper _profileHelper; protected ConfigServer _configServer; protected ApplicationContext _applicationContext; @@ -44,7 +43,7 @@ public class BotController public BotController ( - ILogger logger, + ISptLogger logger, DatabaseService databaseService, BotGenerator botGenerator, BotHelper botHelper, diff --git a/Core/Controllers/ClientLogController.cs b/Core/Controllers/ClientLogController.cs index 8fa61b83..8e61faa1 100644 --- a/Core/Controllers/ClientLogController.cs +++ b/Core/Controllers/ClientLogController.cs @@ -1,7 +1,6 @@ using Core.Annotations; -using Core.Models.Logging; using Core.Models.Spt.Logging; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; using LogLevel = Core.Models.Spt.Logging.LogLevel; namespace Core.Controllers; @@ -9,10 +8,11 @@ namespace Core.Controllers; [Injectable] public class ClientLogController { - private readonly ILogger _logger; + protected ISptLogger _logger; public ClientLogController( - ILogger logger) + ISptLogger logger + ) { _logger = logger; } @@ -45,7 +45,7 @@ public class ClientLogController this._logger.Info(message); break; case LogLevel.CUSTOM: - this._logger.Info(message/* TODO: , color.ToString(), backgroundColor.ToString()*/); + this._logger.Info(message /* TODO: , color.ToString(), backgroundColor.ToString()*/); break; case LogLevel.DEBUG: this._logger.Debug(message); diff --git a/Core/Controllers/CustomizationController.cs b/Core/Controllers/CustomizationController.cs index cc95fa14..81dc2b20 100644 --- a/Core/Controllers/CustomizationController.cs +++ b/Core/Controllers/CustomizationController.cs @@ -7,11 +7,12 @@ using Core.Models.Eft.Hideout; using Core.Models.Eft.ItemEvent; using Core.Models.Eft.Profile; using Core.Models.Enums; +using Core.Models.Utils; using Core.Routers; using Core.Servers; using Core.Services; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + using Product = Core.Models.Eft.ItemEvent.Product; namespace Core.Controllers; @@ -19,7 +20,7 @@ namespace Core.Controllers; [Injectable] public class CustomizationController { - protected ILogger _logger; + protected ISptLogger _logger; protected EventOutputHolder _eventOutputHolder; protected DatabaseService _databaseService; protected SaveServer _saveServer; @@ -29,7 +30,7 @@ public class CustomizationController public CustomizationController ( - ILogger logger, + ISptLogger logger, EventOutputHolder eventOutputHolder, DatabaseService databaseService, SaveServer saveServer, diff --git a/Core/Controllers/DialogueController.cs b/Core/Controllers/DialogueController.cs index 2f86f5a8..f3830bf3 100644 --- a/Core/Controllers/DialogueController.cs +++ b/Core/Controllers/DialogueController.cs @@ -13,12 +13,12 @@ namespace Core.Controllers; [Injectable] public class DialogueController { - private readonly DialogueHelper _dialogueHelper; - private readonly ProfileHelper _profileHelper; - private readonly ConfigServer _configServer; - private readonly SaveServer _saveServer; - private readonly List _dialogueChatBots; - private readonly CoreConfig _coreConfig; + protected DialogueHelper _dialogueHelper; + protected ProfileHelper _profileHelper; + protected ConfigServer _configServer; + protected SaveServer _saveServer; + protected List _dialogueChatBots; + protected CoreConfig _coreConfig; public DialogueController( DialogueHelper dialogueHelper, diff --git a/Core/Controllers/GameController.cs b/Core/Controllers/GameController.cs index 6ebb43de..ec0d79da 100644 --- a/Core/Controllers/GameController.cs +++ b/Core/Controllers/GameController.cs @@ -7,51 +7,52 @@ using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.External; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class GameController { - private readonly ILogger _logger; - private readonly ConfigServer _configServer; - private readonly DatabaseService _databaseService; + protected ISptLogger _logger; + protected ConfigServer _configServer; + protected DatabaseService _databaseService; - private readonly TimeUtil _timeUtil; + protected TimeUtil _timeUtil; - // private readonly PreSptModLoader _preSptModLoader; - private readonly HttpServerHelper _httpServerHelper; - private readonly InventoryHelper _inventoryHelper; - private readonly RandomUtil _randomUtil; - private readonly HideoutHelper _hideoutHelper; - private readonly ProfileHelper _profileHelper; - private readonly ProfileFixerService _profileFixerService; - private readonly LocalisationService _localisationService; - private readonly PostDbLoadService _postDbLoadService; - private readonly CustomLocationWaveService _customLocationWaveService; - private readonly OpenZoneService _openZoneService; - private readonly SeasonalEventService _seasonalEventService; - private readonly ItemBaseClassService _itemBaseClassService; - private readonly GiftService _giftService; - private readonly RaidTimeAdjustmentService _raidTimeAdjustmentService; - private readonly ProfileActivityService _profileActivityService; - private readonly ApplicationContext _applicationContext; - //private readonly PreSptModLoader preSptModLoader - private readonly ICloner _cloner; + // protected PreSptModLoader _preSptModLoader; + protected HttpServerHelper _httpServerHelper; + protected InventoryHelper _inventoryHelper; + protected RandomUtil _randomUtil; + protected HideoutHelper _hideoutHelper; + protected ProfileHelper _profileHelper; + protected ProfileFixerService _profileFixerService; + protected LocalisationService _localisationService; + protected PostDbLoadService _postDbLoadService; + protected CustomLocationWaveService _customLocationWaveService; + protected OpenZoneService _openZoneService; + protected SeasonalEventService _seasonalEventService; + protected ItemBaseClassService _itemBaseClassService; + protected GiftService _giftService; + protected RaidTimeAdjustmentService _raidTimeAdjustmentService; + protected ProfileActivityService _profileActivityService; + protected ApplicationContext _applicationContext; + //protected PreSptModLoader preSptModLoader + protected ICloner _cloner; - private readonly CoreConfig _coreConfig; - private readonly HttpConfig _httpConfig; - private readonly RagfairConfig _ragfairConfig; - private readonly HideoutConfig _hideoutConfig; - private readonly BotConfig _botConfig; + protected CoreConfig _coreConfig; + protected HttpConfig _httpConfig; + protected RagfairConfig _ragfairConfig; + protected HideoutConfig _hideoutConfig; + protected BotConfig _botConfig; public GameController( - ILogger logger, + ISptLogger logger, ConfigServer configServer, DatabaseService databaseService, TimeUtil timeUtil, diff --git a/Core/Controllers/HideoutController.cs b/Core/Controllers/HideoutController.cs index d5c902fc..664d6f2e 100644 --- a/Core/Controllers/HideoutController.cs +++ b/Core/Controllers/HideoutController.cs @@ -6,44 +6,45 @@ using Core.Models.Eft.Hideout; using Core.Models.Eft.ItemEvent; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Routers; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class HideoutController { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly TimeUtil _timeUtil; - private readonly DatabaseService _databaseService; - private readonly RandomUtil _randomUtil; - private readonly InventoryHelper _inventoryHelper; - private readonly ItemHelper _itemHelper; - private readonly SaveServer _saveServer; - private readonly PlayerService _playerService; - private readonly PresetHelper _presetHelper; - private readonly PaymentHelper _paymentHelper; - private readonly EventOutputHolder _eventOutputHolder; - private readonly HttpResponseUtil _httpResponseUtil; - private readonly ProfileHelper _profileHelper; - private readonly HideoutHelper _hideoutHelper; - private readonly ScavCaseRewardGenerator _scavCaseRewardGenerator; - private readonly LocalisationService _localisationService; - private readonly ProfileActivityService _profileActivityService; - private readonly FenceService _fenceService; - private readonly CircleOfCultistService _circleOfCultistService; - private readonly ICloner _cloner; - private readonly ConfigServer _configServer; - private readonly HideoutConfig _hideoutConfig; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected TimeUtil _timeUtil; + protected DatabaseService _databaseService; + protected RandomUtil _randomUtil; + protected InventoryHelper _inventoryHelper; + protected ItemHelper _itemHelper; + protected SaveServer _saveServer; + protected PlayerService _playerService; + protected PresetHelper _presetHelper; + protected PaymentHelper _paymentHelper; + protected EventOutputHolder _eventOutputHolder; + protected HttpResponseUtil _httpResponseUtil; + protected ProfileHelper _profileHelper; + protected HideoutHelper _hideoutHelper; + protected ScavCaseRewardGenerator _scavCaseRewardGenerator; + protected LocalisationService _localisationService; + protected ProfileActivityService _profileActivityService; + protected FenceService _fenceService; + protected CircleOfCultistService _circleOfCultistService; + protected ICloner _cloner; + protected ConfigServer _configServer; + protected HideoutConfig _hideoutConfig; public HideoutController( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, TimeUtil timeUtil, DatabaseService databaseService, diff --git a/Core/Controllers/InRaidController.cs b/Core/Controllers/InRaidController.cs index be61b5f1..8b2e4bb3 100644 --- a/Core/Controllers/InRaidController.cs +++ b/Core/Controllers/InRaidController.cs @@ -4,16 +4,17 @@ using Core.Helpers; using Core.Models.Eft.InRaid; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class InRaidController { - protected ILogger _logger; + protected ISptLogger _logger; protected SaveServer _saveServer; protected ProfileHelper _profileHelper; protected LocalisationService _localisationService; @@ -25,7 +26,7 @@ public class InRaidController public InRaidController ( - ILogger logger, + ISptLogger logger, SaveServer saveServer, ProfileHelper profileHelper, LocalisationService localisationService, diff --git a/Core/Controllers/LauncherController.cs b/Core/Controllers/LauncherController.cs index bc1f997d..09cebcec 100644 --- a/Core/Controllers/LauncherController.cs +++ b/Core/Controllers/LauncherController.cs @@ -7,11 +7,12 @@ using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.Spt.Config; using Core.Models.Spt.Mod; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Extensions; -using ILogger = Core.Models.Utils.ILogger; + using Info = Core.Models.Eft.Profile.Info; namespace Core.Controllers; @@ -21,7 +22,7 @@ public class LauncherController { protected CoreConfig _coreConfig; - protected ILogger _logger; + protected ISptLogger _logger; protected HashUtil _hashUtil; protected TimeUtil _timeUtil; protected RandomUtil _randomUtil; @@ -33,7 +34,7 @@ public class LauncherController public LauncherController( - Models.Utils.ILogger logger, + ISptLogger logger, HashUtil hashUtil, TimeUtil timeUtil, RandomUtil randomUtil, diff --git a/Core/Controllers/LocationController.cs b/Core/Controllers/LocationController.cs index 0aafbac6..0e0a388a 100644 --- a/Core/Controllers/LocationController.cs +++ b/Core/Controllers/LocationController.cs @@ -2,22 +2,23 @@ using Core.Annotations; using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Location; +using Core.Models.Utils; using Core.Services; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class LocationController { - private readonly ILogger _logger; - private readonly DatabaseService _databaseService; - private readonly AirdropService _airdropService; - private readonly ICloner _cloner; + protected ISptLogger _logger; + protected DatabaseService _databaseService; + protected AirdropService _airdropService; + protected ICloner _cloner; public LocationController( - ILogger logger, + ISptLogger logger, DatabaseService databaseService, AirdropService airdropService, ICloner cloner) diff --git a/Core/Controllers/NoteController.cs b/Core/Controllers/NoteController.cs index 7621eae0..8d77d662 100644 --- a/Core/Controllers/NoteController.cs +++ b/Core/Controllers/NoteController.cs @@ -9,7 +9,7 @@ namespace Core.Controllers; [Injectable] public class NoteController { - private readonly EventOutputHolder _eventOutputHolder; + protected EventOutputHolder _eventOutputHolder; public NoteController( EventOutputHolder eventOutputHolder) diff --git a/Core/Controllers/NotifierController.cs b/Core/Controllers/NotifierController.cs index 987550c2..ad6cb10c 100644 --- a/Core/Controllers/NotifierController.cs +++ b/Core/Controllers/NotifierController.cs @@ -7,8 +7,8 @@ namespace Core.Controllers; [Injectable] public class NotifierController { - private readonly HttpServerHelper _httpServerHelper; - private readonly NotifierHelper _notifierHelper; + protected HttpServerHelper _httpServerHelper; + protected NotifierHelper _notifierHelper; public NotifierController( HttpServerHelper httpServerHelper, diff --git a/Core/Controllers/PresetController.cs b/Core/Controllers/PresetController.cs index 4a947a4b..de275015 100644 --- a/Core/Controllers/PresetController.cs +++ b/Core/Controllers/PresetController.cs @@ -1,20 +1,21 @@ using Core.Annotations; using Core.Helpers; using Core.Models.Eft.Common; +using Core.Models.Utils; using Core.Services; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class PresetController { - private readonly ILogger _logger; - private readonly PresetHelper _presetHelper; - private readonly DatabaseService _databaseService; + protected ISptLogger _logger; + protected PresetHelper _presetHelper; + protected DatabaseService _databaseService; public PresetController( - ILogger logger, + ISptLogger logger, PresetHelper presetHelper, DatabaseService databaseService ) diff --git a/Core/Controllers/PrestigeController.cs b/Core/Controllers/PrestigeController.cs index 320c2aa8..14fd2d20 100644 --- a/Core/Controllers/PrestigeController.cs +++ b/Core/Controllers/PrestigeController.cs @@ -5,29 +5,30 @@ using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Inventory; using Core.Models.Eft.Prestige; using Core.Models.Eft.Profile; +using Core.Models.Utils; using Core.Routers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class PrestigeController { - private readonly ILogger _logger; - private readonly TimeUtil _timeUtil; - private readonly InventoryHelper _inventoryHelper; - private readonly ProfileHelper _profileHelper; - private readonly EventOutputHolder _eventOutputHolder; - private readonly CreateProfileService _createProfileService; + protected ISptLogger _logger; + protected TimeUtil _timeUtil; + protected InventoryHelper _inventoryHelper; + protected ProfileHelper _profileHelper; + protected EventOutputHolder _eventOutputHolder; + protected CreateProfileService _createProfileService; private DatabaseService _databaseService; - private readonly ICloner _cloner; + protected ICloner _cloner; public PrestigeController ( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, InventoryHelper inventoryHelper, ProfileHelper profileHelper, diff --git a/Core/Controllers/ProfileController.cs b/Core/Controllers/ProfileController.cs index 26c70203..70681405 100644 --- a/Core/Controllers/ProfileController.cs +++ b/Core/Controllers/ProfileController.cs @@ -5,6 +5,7 @@ using Core.Models.Eft.Common; using Core.Models.Eft.Launcher; using Core.Models.Eft.Profile; using Core.Models.Enums; +using Core.Models.Utils; using Core.Routers; using Core.Servers; using Core.Services; @@ -16,7 +17,7 @@ namespace Core.Controllers; [Injectable] public class ProfileController { - protected Models.Utils.ILogger _logger; + protected ISptLogger _logger; protected HashUtil _hashUtil; protected ICloner _cloner; @@ -26,22 +27,22 @@ public class ProfileController protected ItemHelper _itemHelper; protected ProfileFixerService _profileFixerService; protected LocalisationService _localisationService; - private readonly CreateProfileService _createProfileService; + protected CreateProfileService _createProfileService; protected SeasonalEventService _seasonalEventService; // TODO: MailSendService mailSendService: MailSendService protected PlayerScavGenerator _playerScavGenerator; - private readonly EventOutputHolder _eventOutputHolder; + protected EventOutputHolder _eventOutputHolder; protected TraderHelper _traderHelper; protected DialogueHelper _dialogueHelper; protected QuestHelper _questHelper; - private readonly QuestRewardHelper _questRewardHelper; + protected QuestRewardHelper _questRewardHelper; protected ProfileHelper _profileHelper; public ProfileController( - Models.Utils.ILogger logger, + ISptLogger logger, HashUtil hashUtil, ICloner cloner, TimeUtil timeUtil, diff --git a/Core/Controllers/QuestController.cs b/Core/Controllers/QuestController.cs index 7d24f47e..ddc46aa1 100644 --- a/Core/Controllers/QuestController.cs +++ b/Core/Controllers/QuestController.cs @@ -4,22 +4,23 @@ using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Eft.ItemEvent; using Core.Models.Eft.Quests; +using Core.Models.Utils; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class QuestController { - private readonly ILogger _logger; - private readonly TimeUtil _timeUtil; - private readonly HttpResponseUtil _httpResponseUtil; - private readonly QuestHelper _questHelper; - private readonly QuestRewardHelper _questRewardHelper; + protected ISptLogger _logger; + protected TimeUtil _timeUtil; + protected HttpResponseUtil _httpResponseUtil; + protected QuestHelper _questHelper; + protected QuestRewardHelper _questRewardHelper; public QuestController( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, HttpResponseUtil httpResponseUtil, QuestHelper questHelper, diff --git a/Core/Controllers/TradeController.cs b/Core/Controllers/TradeController.cs index 5ff11081..2a42b204 100644 --- a/Core/Controllers/TradeController.cs +++ b/Core/Controllers/TradeController.cs @@ -7,40 +7,41 @@ using Core.Models.Eft.Ragfair; using Core.Models.Eft.Trade; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Routers; using Core.Servers; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class TradeController { - private readonly ILogger _logger; - private readonly DatabaseService _databaseService; - private readonly EventOutputHolder _eventOutputHolder; - private readonly TradeHelper _tradeHelper; - private readonly TimeUtil _timeUtil; - private readonly HashUtil _hashUtil; - private readonly ItemHelper _itemHelper; - private readonly ProfileHelper _profileHelper; - private readonly RagfairOfferHelper _ragfairOfferHelper; - private readonly TraderHelper _traderHelper; - // private readonly RagfairServer _ragfairServer; - private readonly HttpResponseUtil _httpResponseUtil; - private readonly LocalisationService _localisationService; - private readonly RagfairPriceService _ragfairPriceService; - // private readonly MailSendService _mailSendService; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected DatabaseService _databaseService; + protected EventOutputHolder _eventOutputHolder; + protected TradeHelper _tradeHelper; + protected TimeUtil _timeUtil; + protected HashUtil _hashUtil; + protected ItemHelper _itemHelper; + protected ProfileHelper _profileHelper; + protected RagfairOfferHelper _ragfairOfferHelper; + protected TraderHelper _traderHelper; + // protected RagfairServer _ragfairServer; + protected HttpResponseUtil _httpResponseUtil; + protected LocalisationService _localisationService; + protected RagfairPriceService _ragfairPriceService; + // protected MailSendService _mailSendService; + protected ConfigServer _configServer; - private readonly RagfairConfig _ragfairConfig; - private readonly TraderConfig _traderConfig; + protected RagfairConfig _ragfairConfig; + protected TraderConfig _traderConfig; public TradeController ( - ILogger logger, + ISptLogger logger, DatabaseService databaseService, EventOutputHolder eventOutputHolder, TradeHelper tradeHelper, diff --git a/Core/Controllers/TraderController.cs b/Core/Controllers/TraderController.cs index 30e8fa59..dbe964c2 100644 --- a/Core/Controllers/TraderController.cs +++ b/Core/Controllers/TraderController.cs @@ -6,18 +6,19 @@ using Core.Models.Eft.Game; using Core.Models.Eft.ItemEvent; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class TraderController { - private ILogger _logger; + private ISptLogger _logger; private TimeUtil _timeUtil; private DatabaseService _databaseService; private TraderAssortHelper _traderAssortHelper; @@ -36,7 +37,7 @@ public class TraderController public TraderController ( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, DatabaseService databaseService, TraderAssortHelper traderAssortHelper, diff --git a/Core/Controllers/WeatherController.cs b/Core/Controllers/WeatherController.cs index a670419c..7b6023dc 100644 --- a/Core/Controllers/WeatherController.cs +++ b/Core/Controllers/WeatherController.cs @@ -5,26 +5,27 @@ using Core.Models.Eft.Weather; using Core.Models.Enums; using Core.Models.Spt.Config; using Core.Models.Spt.Weather; +using Core.Models.Utils; using Core.Servers; using Core.Services; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Controllers; [Injectable] public class WeatherController { - private readonly ILogger _logger; - private readonly WeatherGenerator _weatherGenerator; - private readonly SeasonalEventService _seasonalEventService; - private readonly RaidWeatherService _raidWeatherService; - private readonly WeatherHelper _weatherHelper; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected WeatherGenerator _weatherGenerator; + protected SeasonalEventService _seasonalEventService; + protected RaidWeatherService _raidWeatherService; + protected WeatherHelper _weatherHelper; + protected ConfigServer _configServer; - private readonly WeatherConfig _weatherConfig; + protected WeatherConfig _weatherConfig; public WeatherController( - ILogger logger, + ISptLogger logger, WeatherGenerator weatherGenerator, SeasonalEventService seasonalEventService, RaidWeatherService raidWeatherService, diff --git a/Core/Controllers/WishlistController.cs b/Core/Controllers/WishlistController.cs index df930fe6..6558046b 100644 --- a/Core/Controllers/WishlistController.cs +++ b/Core/Controllers/WishlistController.cs @@ -9,7 +9,7 @@ namespace Core.Controllers; [Injectable] public class WishlistController { - private readonly EventOutputHolder _eventOutputHolder; + protected EventOutputHolder _eventOutputHolder; public WishlistController( EventOutputHolder eventOutputHolder) diff --git a/Core/Generators/BotGenerator.cs b/Core/Generators/BotGenerator.cs index d22c1594..d18486d4 100644 --- a/Core/Generators/BotGenerator.cs +++ b/Core/Generators/BotGenerator.cs @@ -7,40 +7,41 @@ using Core.Models.Enums; using Core.Models.Enums.RaidSettings; using Core.Models.Spt.Bots; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; using BodyPart = Core.Models.Eft.Common.Tables.BodyPart; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Generators; [Injectable] public class BotGenerator { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly RandomUtil _randomUtil; - private readonly TimeUtil _timeUtil; - private readonly ProfileHelper _profileHelper; - private readonly DatabaseService _databaseService; - private readonly BotInventoryGenerator _botInventoryGenerator; - private readonly BotLevelGenerator _botLevelGenerator; - private readonly BotEquipmentFilterService _botEquipmentFilterService; - private readonly WeightedRandomHelper _weightedRandomHelper; - private readonly BotHelper _botHelper; - private readonly BotGeneratorHelper _botGeneratorHelper; - private readonly SeasonalEventService _seasonalEventService; - private readonly ItemFilterService _itemFilterService; - private readonly BotNameService _botNameService; - private readonly ConfigServer _configServer; - private readonly ICloner _cloner; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected RandomUtil _randomUtil; + protected TimeUtil _timeUtil; + protected ProfileHelper _profileHelper; + protected DatabaseService _databaseService; + protected BotInventoryGenerator _botInventoryGenerator; + protected BotLevelGenerator _botLevelGenerator; + protected BotEquipmentFilterService _botEquipmentFilterService; + protected WeightedRandomHelper _weightedRandomHelper; + protected BotHelper _botHelper; + protected BotGeneratorHelper _botGeneratorHelper; + protected SeasonalEventService _seasonalEventService; + protected ItemFilterService _itemFilterService; + protected BotNameService _botNameService; + protected ConfigServer _configServer; + protected ICloner _cloner; private BotConfig _botConfig; private PmcConfig _pmcConfig; public BotGenerator( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, RandomUtil randomUtil, TimeUtil timeUtil, diff --git a/Core/Generators/BotInventoryGenerator.cs b/Core/Generators/BotInventoryGenerator.cs index b1aaaefd..dfe45b13 100644 --- a/Core/Generators/BotInventoryGenerator.cs +++ b/Core/Generators/BotInventoryGenerator.cs @@ -6,39 +6,41 @@ using Core.Models.Eft.Match; using Core.Models.Enums; using Core.Models.Spt.Bots; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; +using Core.Services; using Core.Utils; using Equipment = Core.Models.Eft.Common.Tables.Equipment; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Generators; [Injectable] public class BotInventoryGenerator { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly RandomUtil _randomUtil; - private readonly DatabaseService _databaseService; - private readonly ApplicationContext _applicationContext; - private readonly BotWeaponGenerator _botWeaponGenerator; - private readonly BotLootGenerator _botLootGenerator; - private readonly BotGeneratorHelper _botGeneratorHelper; - private readonly ProfileHelper _profileHelper; - private readonly BotHelper _botHelper; - private readonly WeightedRandomHelper _weightedRandomHelper; - private readonly ItemHelper _itemHelper; - private readonly WeatherHelper _weatherHelper; - private readonly LocalisationService _localisationService; - private readonly BotEquipmentFilterService _botEquipmentFilterService; - private readonly BotEquipmentModPoolService _botEquipmentModPoolService; - private readonly BotEquipmentModGenerator _botEquipmentModGenerator; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected RandomUtil _randomUtil; + protected DatabaseService _databaseService; + protected ApplicationContext _applicationContext; + protected BotWeaponGenerator _botWeaponGenerator; + protected BotLootGenerator _botLootGenerator; + protected BotGeneratorHelper _botGeneratorHelper; + protected ProfileHelper _profileHelper; + protected BotHelper _botHelper; + protected WeightedRandomHelper _weightedRandomHelper; + protected ItemHelper _itemHelper; + protected WeatherHelper _weatherHelper; + protected LocalisationService _localisationService; + protected BotEquipmentFilterService _botEquipmentFilterService; + protected BotEquipmentModPoolService _botEquipmentModPoolService; + protected BotEquipmentModGenerator _botEquipmentModGenerator; + protected ConfigServer _configServer; private BotConfig _botConfig; public BotInventoryGenerator( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, RandomUtil randomUtil, DatabaseService databaseService, diff --git a/Core/Generators/BotLevelGenerator.cs b/Core/Generators/BotLevelGenerator.cs index e3efb15f..95a977a2 100644 --- a/Core/Generators/BotLevelGenerator.cs +++ b/Core/Generators/BotLevelGenerator.cs @@ -3,22 +3,23 @@ using Core.Models.Common; using Core.Models.Eft.Bot; using Core.Models.Eft.Common.Tables; using Core.Models.Spt.Bots; +using Core.Models.Utils; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Generators; [Injectable] public class BotLevelGenerator { - private readonly ILogger _logger; - private readonly RandomUtil _randomUtil; - private readonly MathUtil _mathUtil; - private readonly DatabaseService _databaseService; + protected ISptLogger _logger; + protected RandomUtil _randomUtil; + protected MathUtil _mathUtil; + protected DatabaseService _databaseService; public BotLevelGenerator( - ILogger logger, + ISptLogger logger, RandomUtil randomUtil, MathUtil mathUtil, DatabaseService databaseService) diff --git a/Core/Generators/PlayerScavGenerator.cs b/Core/Generators/PlayerScavGenerator.cs index 84f6fc96..3f8fe537 100644 --- a/Core/Generators/PlayerScavGenerator.cs +++ b/Core/Generators/PlayerScavGenerator.cs @@ -4,39 +4,40 @@ using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Generators; [Injectable] public class PlayerScavGenerator { - private readonly ILogger _logger; - private readonly RandomUtil _randomUtil; - private readonly DatabaseService _databaseService; - private readonly HashUtil _hashUtil; - private readonly ItemHelper _itemHelper; - private readonly BotGeneratorHelper _botGeneratorHelper; - private readonly SaveServer _saveServer; - private readonly ProfileHelper _profileHelper; - private readonly BotHelper _botHelper; - private readonly FenceService _fenceService; - private readonly BotLootCacheService _botLootCacheService; - private readonly LocalisationService _localisationService; - private readonly BotGenerator _botGenerator; - private readonly ConfigServer _configServer; - private readonly ICloner _cloner; - private readonly TimeUtil _timeUtil; + protected ISptLogger _logger; + protected RandomUtil _randomUtil; + protected DatabaseService _databaseService; + protected HashUtil _hashUtil; + protected ItemHelper _itemHelper; + protected BotGeneratorHelper _botGeneratorHelper; + protected SaveServer _saveServer; + protected ProfileHelper _profileHelper; + protected BotHelper _botHelper; + protected FenceService _fenceService; + protected BotLootCacheService _botLootCacheService; + protected LocalisationService _localisationService; + protected BotGenerator _botGenerator; + protected ConfigServer _configServer; + protected ICloner _cloner; + protected TimeUtil _timeUtil; private PlayerScavConfig _playerScavConfig; public PlayerScavGenerator ( - ILogger logger, + ISptLogger logger, RandomUtil randomUtil, DatabaseService databaseService, HashUtil hashUtil, diff --git a/Core/Generators/WeatherGenerator.cs b/Core/Generators/WeatherGenerator.cs index 24f59c84..1e8c14ef 100644 --- a/Core/Generators/WeatherGenerator.cs +++ b/Core/Generators/WeatherGenerator.cs @@ -12,13 +12,13 @@ namespace Core.Generators; [Injectable] public class WeatherGenerator { - private readonly TimeUtil _timeUtil; - private readonly SeasonalEventService _seasonalEventService; - private readonly WeatherHelper _weatherHelper; - private readonly ConfigServer _configServer; - private readonly WeightedRandomHelper _weightedRandomHelper; - private readonly RandomUtil _randomUtil; - private readonly WeatherConfig _weatherConfig; + protected TimeUtil _timeUtil; + protected SeasonalEventService _seasonalEventService; + protected WeatherHelper _weatherHelper; + protected ConfigServer _configServer; + protected WeightedRandomHelper _weightedRandomHelper; + protected RandomUtil _randomUtil; + protected WeatherConfig _weatherConfig; public WeatherGenerator( TimeUtil timeUtil, diff --git a/Core/Helpers/BotGeneratorHelper.cs b/Core/Helpers/BotGeneratorHelper.cs index ecb8fd73..829e7c49 100644 --- a/Core/Helpers/BotGeneratorHelper.cs +++ b/Core/Helpers/BotGeneratorHelper.cs @@ -9,8 +9,8 @@ namespace Core.Helpers; [Injectable] public class BotGeneratorHelper { - private readonly ConfigServer _configServer; - private readonly PmcConfig _pmcConfig; + protected ConfigServer _configServer; + protected PmcConfig _pmcConfig; public BotGeneratorHelper( ConfigServer configServer diff --git a/Core/Helpers/BotHelper.cs b/Core/Helpers/BotHelper.cs index f6d8189a..8e495e5c 100644 --- a/Core/Helpers/BotHelper.cs +++ b/Core/Helpers/BotHelper.cs @@ -4,29 +4,30 @@ using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Match; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Helpers; [Injectable] public class BotHelper { - private readonly ILogger _logger; - private readonly DatabaseService _databaseService; - private readonly RandomUtil _randomUtil; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected DatabaseService _databaseService; + protected RandomUtil _randomUtil; + protected ConfigServer _configServer; - private readonly BotConfig _botConfig; - private readonly PmcConfig _pmcConfig; + protected BotConfig _botConfig; + protected PmcConfig _pmcConfig; - private readonly List _pmcNames = ["usec", "bear", "pmc", "pmcbear", "pmcusec"]; + protected List _pmcNames = ["usec", "bear", "pmc", "pmcbear", "pmcusec"]; public BotHelper ( - ILogger logger, + ISptLogger logger, DatabaseService databaseService, RandomUtil randomUtil, ConfigServer configServer diff --git a/Core/Helpers/DialogueHelper.cs b/Core/Helpers/DialogueHelper.cs index afef1631..7415cfcf 100644 --- a/Core/Helpers/DialogueHelper.cs +++ b/Core/Helpers/DialogueHelper.cs @@ -1,28 +1,29 @@ using Core.Annotations; using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Profile; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Helpers; [Injectable] public class DialogueHelper { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly SaveServer _saveServer; - private readonly DatabaseServer _databaseServer; - private readonly NotifierHelper _notifierHelper; - private readonly NotificationSendHelper _notificationSendHelper; - private readonly LocalisationService _localisationService; - private readonly ItemHelper _itemHelper; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected SaveServer _saveServer; + protected DatabaseServer _databaseServer; + protected NotifierHelper _notifierHelper; + protected NotificationSendHelper _notificationSendHelper; + protected LocalisationService _localisationService; + protected ItemHelper _itemHelper; public DialogueHelper ( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, SaveServer saveServer, DatabaseServer databaseServer, diff --git a/Core/Helpers/ItemHelper.cs b/Core/Helpers/ItemHelper.cs index 313af33f..5142ccad 100644 --- a/Core/Helpers/ItemHelper.cs +++ b/Core/Helpers/ItemHelper.cs @@ -3,31 +3,32 @@ using Core.Annotations; using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Enums; +using Core.Models.Utils; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Helpers; [Injectable] public class ItemHelper { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly JsonUtil _jsonUtil; - private readonly RandomUtil _randomUtil; - private readonly MathUtil _mathUtil; - private readonly DatabaseService _databaseService; - private readonly HandbookHelper _handbookHelper; - private readonly ItemBaseClassService _itemBaseClassService; - private readonly ItemFilterService _itemFilterService; - private readonly LocalisationService _localisationService; - private readonly LocaleService _localeService; - private readonly CompareUtil _compareUtil; - private readonly ICloner _cloner; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected JsonUtil _jsonUtil; + protected RandomUtil _randomUtil; + protected MathUtil _mathUtil; + protected DatabaseService _databaseService; + protected HandbookHelper _handbookHelper; + protected ItemBaseClassService _itemBaseClassService; + protected ItemFilterService _itemFilterService; + protected LocalisationService _localisationService; + protected LocaleService _localeService; + protected CompareUtil _compareUtil; + protected ICloner _cloner; - private readonly List _defaultInvalidBaseTypes = + protected List _defaultInvalidBaseTypes = [ BaseClasses.LOOT_CONTAINER, BaseClasses.MOB_CONTAINER, @@ -40,7 +41,7 @@ public class ItemHelper public ItemHelper ( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, JsonUtil jsonUtil, RandomUtil randomUtil, diff --git a/Core/Helpers/PaymentHelper.cs b/Core/Helpers/PaymentHelper.cs index 54fc6517..40ca5e68 100644 --- a/Core/Helpers/PaymentHelper.cs +++ b/Core/Helpers/PaymentHelper.cs @@ -8,8 +8,8 @@ namespace Core.Helpers; [Injectable] public class PaymentHelper { - private readonly ConfigServer _configServer; - private readonly InventoryConfig _inventoryConfig; + protected ConfigServer _configServer; + protected InventoryConfig _inventoryConfig; public PaymentHelper( ConfigServer configServer) diff --git a/Core/Helpers/ProfileHelper.cs b/Core/Helpers/ProfileHelper.cs index 6c0e2dce..612a472f 100644 --- a/Core/Helpers/ProfileHelper.cs +++ b/Core/Helpers/ProfileHelper.cs @@ -4,6 +4,7 @@ using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; @@ -14,7 +15,7 @@ namespace Core.Helpers; [Injectable] public class ProfileHelper { - protected Models.Utils.ILogger _logger; + protected ISptLogger _logger; protected ICloner _cloner; protected SaveServer _saveServer; @@ -27,6 +28,7 @@ public class ProfileHelper protected HashUtil _hashUtil; public ProfileHelper( + ISptLogger logger, ICloner cloner, SaveServer saveServer, DatabaseService databaseService, @@ -38,6 +40,7 @@ public class ProfileHelper ConfigServer configServer ) { + _logger = logger; _cloner = cloner; _saveServer = saveServer; _databaseService = databaseService; diff --git a/Core/Helpers/QuestHelper.cs b/Core/Helpers/QuestHelper.cs index cc727266..b520af25 100644 --- a/Core/Helpers/QuestHelper.cs +++ b/Core/Helpers/QuestHelper.cs @@ -5,11 +5,12 @@ using Core.Models.Eft.ItemEvent; using Core.Models.Eft.Quests; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + using Product = Core.Models.Eft.ItemEvent.Product; namespace Core.Helpers; @@ -17,18 +18,18 @@ namespace Core.Helpers; [Injectable] public class QuestHelper { - private readonly ILogger _logger; - private readonly TimeUtil _timeUtil; - private readonly DatabaseService _databaseService; - private readonly QuestConditionHelper _questConditionHelper; - private readonly ProfileHelper _profileHelper; - private readonly LocalisationService _localisationService; - private readonly LocaleService _localeService; - private readonly ICloner _cloner; - private readonly QuestConfig _questConfig; + protected ISptLogger _logger; + protected TimeUtil _timeUtil; + protected DatabaseService _databaseService; + protected QuestConditionHelper _questConditionHelper; + protected ProfileHelper _profileHelper; + protected LocalisationService _localisationService; + protected LocaleService _localeService; + protected ICloner _cloner; + protected QuestConfig _questConfig; public QuestHelper( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, DatabaseService databaseService, QuestConditionHelper questConditionHelper, diff --git a/Core/Helpers/QuestRewardHelper.cs b/Core/Helpers/QuestRewardHelper.cs index 5f30e1e5..2508d0b4 100644 --- a/Core/Helpers/QuestRewardHelper.cs +++ b/Core/Helpers/QuestRewardHelper.cs @@ -5,33 +5,34 @@ using Core.Models.Eft.Hideout; using Core.Models.Eft.ItemEvent; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Helpers; [Injectable] public class QuestRewardHelper { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly TimeUtil _timeUtil; - private readonly ItemHelper _itemHelper; - private readonly PaymentHelper _paymentHelper; - private readonly TraderHelper _traderHelper; - private readonly DatabaseService _databaseService; - private readonly QuestConditionHelper _questConditionHelper; - private readonly ProfileHelper _profileHelper; - private readonly PresetHelper _presetHelper; - private readonly LocalisationService _localisationService; - private readonly QuestConfig _questConfig; - private readonly ICloner _cloner; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected TimeUtil _timeUtil; + protected ItemHelper _itemHelper; + protected PaymentHelper _paymentHelper; + protected TraderHelper _traderHelper; + protected DatabaseService _databaseService; + protected QuestConditionHelper _questConditionHelper; + protected ProfileHelper _profileHelper; + protected PresetHelper _presetHelper; + protected LocalisationService _localisationService; + protected QuestConfig _questConfig; + protected ICloner _cloner; public QuestRewardHelper( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, TimeUtil timeUtil, ItemHelper itemHelper, diff --git a/Core/Helpers/TraderHelper.cs b/Core/Helpers/TraderHelper.cs index 79ce6aa6..c3c0bb11 100644 --- a/Core/Helpers/TraderHelper.cs +++ b/Core/Helpers/TraderHelper.cs @@ -5,29 +5,30 @@ using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Helpers; [Injectable] public class TraderHelper { - private readonly ILogger _logger; - private readonly TimeUtil _timeUtil; - private readonly RandomUtil _randomUtil; - private readonly LocalisationService _localisationService; - private readonly ConfigServer _configServer; - private readonly TraderConfig _traderConfig; - private readonly ProfileHelper _profileHelper; - private readonly DatabaseService _databaseService; + protected ISptLogger _logger; + protected TimeUtil _timeUtil; + protected RandomUtil _randomUtil; + protected LocalisationService _localisationService; + protected ConfigServer _configServer; + protected TraderConfig _traderConfig; + protected ProfileHelper _profileHelper; + protected DatabaseService _databaseService; private Dictionary _highestTraderPriceItems = new(); public TraderHelper( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, RandomUtil randomUtil, LocalisationService localisationService, diff --git a/Core/Helpers/WeatherHelper.cs b/Core/Helpers/WeatherHelper.cs index 78bef744..b434cce2 100644 --- a/Core/Helpers/WeatherHelper.cs +++ b/Core/Helpers/WeatherHelper.cs @@ -1,24 +1,25 @@ using Core.Annotations; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Helpers; [Injectable] public class WeatherHelper { - private readonly ILogger _logger; - private readonly TimeUtil _timeUtil; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected TimeUtil _timeUtil; + protected ConfigServer _configServer; - private readonly WeatherConfig _weatherConfig; + protected WeatherConfig _weatherConfig; public WeatherHelper ( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, ConfigServer configServer ) diff --git a/Core/Helpers/WeightedRandomHelper.cs b/Core/Helpers/WeightedRandomHelper.cs index 11cc012c..8c9a35b1 100644 --- a/Core/Helpers/WeightedRandomHelper.cs +++ b/Core/Helpers/WeightedRandomHelper.cs @@ -1,16 +1,18 @@ using Core.Annotations; using Core.Models.Spt.Helper; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; + namespace Core.Helpers; [Injectable] public class WeightedRandomHelper { - private readonly ILogger _logger; + protected ISptLogger _logger; public WeightedRandomHelper( - ILogger logger) + ISptLogger logger + ) { _logger = logger; } diff --git a/Core/Loaders/PostDBModLoader.cs b/Core/Loaders/PostDBModLoader.cs index dceb41b1..e51034cc 100644 --- a/Core/Loaders/PostDBModLoader.cs +++ b/Core/Loaders/PostDBModLoader.cs @@ -1,18 +1,19 @@ using Core.Annotations; using Core.DI; using Core.Models.External; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; + namespace Core.Loaders; [Injectable(InjectableTypeOverride = typeof(OnLoad), TypePriority = OnLoadOrder.PostDBModLoader)] public class PostDBModLoader : OnLoad { - private readonly ILogger _logger; - private readonly IEnumerable _postDbLoadMods; + protected ISptLogger _logger; + protected IEnumerable _postDbLoadMods; public PostDBModLoader( - ILogger logger, + ISptLogger logger, IEnumerable postDbLoadMods ) { diff --git a/Core/Loaders/PostSptModLoader.cs b/Core/Loaders/PostSptModLoader.cs index b2fb475e..6af8edba 100644 --- a/Core/Loaders/PostSptModLoader.cs +++ b/Core/Loaders/PostSptModLoader.cs @@ -1,18 +1,19 @@ using Core.Annotations; using Core.DI; using Core.Models.External; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; + namespace Core.Loaders; [Injectable(InjectableTypeOverride = typeof(OnLoad), TypePriority = OnLoadOrder.PostSptModLoader)] public class PostSptModLoader : OnLoad { - private readonly ILogger _logger; - private readonly IEnumerable _postSptLoadMods; + protected ISptLogger _logger; + protected IEnumerable _postSptLoadMods; public PostSptModLoader( - ILogger logger, + ISptLogger logger, IEnumerable postSptLoadMods ) { diff --git a/Core/Models/Eft/Ws/NotificationEventType.cs b/Core/Models/Eft/Ws/NotificationEventType.cs new file mode 100644 index 00000000..7c068e06 --- /dev/null +++ b/Core/Models/Eft/Ws/NotificationEventType.cs @@ -0,0 +1,43 @@ +namespace Core.Models.Eft.Ws; + +public enum NotificationEventType +{ + AssortmentUnlockRule, + ExamineItems, + ExamineAllItems, + ForceLogout, + RagfairOfferSold, + RagfairNewRating, + RagfairRatingChange, + new_message, + ping, + TraderSalesSum, + trader_supply, + TraderStanding, + UnlockTrader, + groupMatchRaidSettings, + groupMatchRaidNotReady, + groupMatchRaidReady, + groupMatchInviteAccept, + groupMatchInviteDecline, + groupMatchInviteSend, + groupMatchLeaderChanged, + groupMatchStartGame, + groupMatchUserLeave, + groupMatchWasRemoved, + groupMatchUserHasBadVersion, + userConfirmed, + UserMatched, + userMatchOver, + channel_deleted, + friendListRequestAccept, + friendListRequestDecline, + friendListNewRequest, + youAreRemovedFromFriendList, + YouWereAddedToIgnoreList, + youAreRemoveFromIgnoreList, + ProfileLockTimer, + StashRows, + SkillPoints, + tournamentWarning, +} diff --git a/Core/Models/Eft/Ws/WsNotificationEvent.cs b/Core/Models/Eft/Ws/WsNotificationEvent.cs index d1db9abf..cd785e85 100644 --- a/Core/Models/Eft/Ws/WsNotificationEvent.cs +++ b/Core/Models/Eft/Ws/WsNotificationEvent.cs @@ -5,8 +5,8 @@ namespace Core.Models.Eft.Ws; public class WsNotificationEvent { [JsonPropertyName("type")] - public string? EventType { get; set; } + public NotificationEventType? EventType { get; set; } [JsonPropertyName("eventId")] public string? EventIdentifier { get; set; } -} \ No newline at end of file +} diff --git a/Core/Models/Eft/Ws/WsPing.cs b/Core/Models/Eft/Ws/WsPing.cs index b044de10..f320da8e 100644 --- a/Core/Models/Eft/Ws/WsPing.cs +++ b/Core/Models/Eft/Ws/WsPing.cs @@ -2,4 +2,9 @@ namespace Core.Models.Eft.Ws; public class WsPing : WsNotificationEvent { -} \ No newline at end of file + public WsPing() + { + EventType = NotificationEventType.ping; + EventIdentifier = "ping"; + } +} diff --git a/Core/Models/Utils/ILogger.cs b/Core/Models/Utils/ILogger.cs deleted file mode 100644 index e83b7b69..00000000 --- a/Core/Models/Utils/ILogger.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Core.Models.Logging; - -namespace Core.Models.Utils; - -public interface ILogger -{ - // TODO: Removing these 4 methods for now, revisit in the future - // void WriteToLogFile(string data); - // void Log(string data, LogTextColor? color, string? backgroundColor = null); - void LogWithColor(string data, LogTextColor? textColor = null, LogBackgroundColor? backgroundColor = null); - void Success(string data); - void Error(string data); - void Warning(string data); - void Info(string data); - void Debug(string data); - void Critical(string data); -} diff --git a/Core/Models/Utils/ISptLogger.cs b/Core/Models/Utils/ISptLogger.cs new file mode 100644 index 00000000..8f8f6afe --- /dev/null +++ b/Core/Models/Utils/ISptLogger.cs @@ -0,0 +1,17 @@ +using Core.Models.Logging; + +namespace Core.Models.Utils; + +public interface ISptLogger +{ + // TODO: Removing these 4 methods for now, revisit in the future + // void WriteToLogFile(string data); + // void Log(string data, LogTextColor? color, string? backgroundColor = null); + void LogWithColor(string data, Exception? ex = null, LogTextColor? textColor = null, LogBackgroundColor? backgroundColor = null); + void Success(string data, Exception? ex = null); + void Error(string data, Exception? ex = null); + void Warning(string data, Exception? ex = null); + void Info(string data, Exception? ex = null); + void Debug(string data, Exception? ex = null); + void Critical(string data, Exception? ex = null); +} diff --git a/Core/Routers/EventOutputHolder.cs b/Core/Routers/EventOutputHolder.cs index c1667bc1..fa0764d1 100644 --- a/Core/Routers/EventOutputHolder.cs +++ b/Core/Routers/EventOutputHolder.cs @@ -11,11 +11,11 @@ namespace Core.Routers; [Injectable] public class EventOutputHolder { - private readonly ProfileHelper _profileHelper; - private readonly TimeUtil _timeUtil; - private readonly ICloner _cloner; + protected ProfileHelper _profileHelper; + protected TimeUtil _timeUtil; + protected ICloner _cloner; - private readonly Dictionary _outputStore = new(); + protected Dictionary _outputStore = new(); public EventOutputHolder( ProfileHelper profileHelper, diff --git a/Core/Routers/HttpRouter.cs b/Core/Routers/HttpRouter.cs index a05ef642..24a635d1 100644 --- a/Core/Routers/HttpRouter.cs +++ b/Core/Routers/HttpRouter.cs @@ -7,8 +7,8 @@ namespace Core.Routers; [Injectable] public class HttpRouter { - private readonly IEnumerable _staticRouters; - private readonly IEnumerable _dynamicRoutes; + protected IEnumerable _staticRouters; + protected IEnumerable _dynamicRoutes; public HttpRouter( IEnumerable staticRouters, diff --git a/Core/Routers/ItemEvents/HideoutItemEventRouter.cs b/Core/Routers/ItemEvents/HideoutItemEventRouter.cs index 43eedc00..c1103424 100644 --- a/Core/Routers/ItemEvents/HideoutItemEventRouter.cs +++ b/Core/Routers/ItemEvents/HideoutItemEventRouter.cs @@ -11,7 +11,7 @@ namespace Core.Routers.ItemEvents; [Injectable(InjectableTypeOverride = typeof(ItemEventRouterDefinition))] public class HideoutItemEventRouter : ItemEventRouterDefinition { - private readonly HideoutCallbacks _hideoutCallbacks; + protected HideoutCallbacks _hideoutCallbacks; public HideoutItemEventRouter ( diff --git a/Core/Routers/ItemEvents/QuestItemEventRouter.cs b/Core/Routers/ItemEvents/QuestItemEventRouter.cs index 7d6171ec..fd65451d 100644 --- a/Core/Routers/ItemEvents/QuestItemEventRouter.cs +++ b/Core/Routers/ItemEvents/QuestItemEventRouter.cs @@ -4,7 +4,7 @@ using Core.DI; using Core.Models.Eft.Common; using Core.Models.Eft.ItemEvent; using Core.Models.Eft.Quests; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Routers.ItemEvents; diff --git a/Core/Servers/ConfigServer.cs b/Core/Servers/ConfigServer.cs index 7275e1e6..2007c9d7 100644 --- a/Core/Servers/ConfigServer.cs +++ b/Core/Servers/ConfigServer.cs @@ -1,22 +1,23 @@ using Core.Annotations; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Servers; [Injectable(InjectionType.Singleton)] public class ConfigServer { - protected ILogger _logger; + protected ISptLogger _logger; protected JsonUtil _jsonUtil; protected FileUtil _fileUtil; protected Dictionary configs = new(); protected readonly string[] acceptableFileExtensions = ["json", "jsonc"]; public ConfigServer( - ILogger logger, + ISptLogger logger, JsonUtil jsonUtil, FileUtil fileUtil ) diff --git a/Core/Servers/Http/SptHttpListener.cs b/Core/Servers/Http/SptHttpListener.cs index b66ac5f4..ce92477f 100644 --- a/Core/Servers/Http/SptHttpListener.cs +++ b/Core/Servers/Http/SptHttpListener.cs @@ -4,10 +4,11 @@ using System.Text; using System.Text.Json; using Core.Annotations; using Core.DI; +using Core.Models.Utils; using Core.Routers; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Servers.Http; @@ -16,15 +17,15 @@ public class SptHttpListener : IHttpListener { protected readonly HttpRouter _router; protected readonly IEnumerable _serializers; - protected readonly ILogger _logger; + protected readonly ISptLogger _logger; protected readonly HttpResponseUtil _httpResponseUtil; protected readonly LocalisationService _localisationService; protected readonly JsonUtil _jsonUtil; public SptHttpListener( HttpRouter httpRouter, // TODO: delay required IEnumerable serializers, - ILogger logger, - // TODO: requestsLogger: ILogger, + ISptLogger logger, + // TODO: requestsLogger: ISptLogger, JsonUtil jsonUtil, HttpResponseUtil httpHttpResponseUtil, LocalisationService localisationService diff --git a/Core/Servers/HttpServer.cs b/Core/Servers/HttpServer.cs index b9df0aa8..c71b4d78 100644 --- a/Core/Servers/HttpServer.cs +++ b/Core/Servers/HttpServer.cs @@ -6,7 +6,8 @@ using Microsoft.Extensions.Primitives; using Core.Annotations; using Core.Models.Enums; using Core.Models.Spt.Config; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; + namespace Core.Servers; @@ -16,15 +17,15 @@ public class HttpServer protected HttpConfig httpConfig; protected bool started; - private readonly ILogger _logger; - private readonly LocalisationService _localisationService; - private readonly ConfigServer _configServer; - private readonly ApplicationContext _applicationContext; - private readonly WebSocketServer _webSocketServer; - private readonly IEnumerable _httpListeners; + protected ISptLogger _logger; + protected LocalisationService _localisationService; + protected ConfigServer _configServer; + protected ApplicationContext _applicationContext; + protected WebSocketServer _webSocketServer; + protected IEnumerable _httpListeners; public HttpServer( - ILogger logger, + ISptLogger logger, LocalisationService localisationService, ConfigServer configServer, ApplicationContext applicationContext, @@ -66,8 +67,7 @@ public class HttpServer { if (context.WebSockets.IsWebSocketRequest) { - return context.WebSockets.AcceptWebSocketAsync() - .ContinueWith(task => Converse(task.Result)); + return _webSocketServer.OnConnection(context); } else { @@ -130,34 +130,6 @@ public class HttpServer return found; } - private void Converse(WebSocket connection) - { - var buffer = new byte[1024 * 4]; - var receive = connection.ReceiveAsync( - new ArraySegment(buffer), CancellationToken.None); - receive.Wait(); - var receiveResult = receive.Result; - - while (!receiveResult.CloseStatus.HasValue) - { - connection.SendAsync( - new ArraySegment(buffer, 0, receiveResult.Count), - receiveResult.MessageType, - receiveResult.EndOfMessage, - CancellationToken.None); - - receive = connection.ReceiveAsync( - new ArraySegment(buffer), CancellationToken.None); - receive.Wait(); - receiveResult = receive.Result; - } - - connection.CloseAsync( - receiveResult.CloseStatus.Value, - receiveResult.CloseStatusDescription, - CancellationToken.None); - } - public bool IsStarted() { return started; diff --git a/Core/Servers/SaveServer.cs b/Core/Servers/SaveServer.cs index 432325eb..9eb8bff0 100644 --- a/Core/Servers/SaveServer.cs +++ b/Core/Servers/SaveServer.cs @@ -6,9 +6,10 @@ using Core.Models.Eft.Common; using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Servers; @@ -28,7 +29,7 @@ public class SaveServer protected readonly JsonUtil _jsonUtil; protected readonly HashUtil _hashUtil; protected readonly LocalisationService _localisationService; - protected readonly ILogger _logger; + protected readonly ISptLogger _logger; protected readonly ConfigServer _configServer; public SaveServer( @@ -37,7 +38,7 @@ public class SaveServer JsonUtil jsonUtil, HashUtil hashUtil, LocalisationService localisationService, - ILogger logger, + ISptLogger logger, ConfigServer configServer ) { diff --git a/Core/Servers/WebSocketServer.cs b/Core/Servers/WebSocketServer.cs index 5ec5648b..4cbcdd05 100644 --- a/Core/Servers/WebSocketServer.cs +++ b/Core/Servers/WebSocketServer.cs @@ -1,8 +1,60 @@ -using Core.Annotations; +using System.Net.WebSockets; +using System.Text; +using Core.Annotations; +using Core.Models.Utils; +using Core.Servers.Ws; +using Core.Utils; namespace Core.Servers; [Injectable(InjectionType.Singleton)] public class WebSocketServer { -} \ No newline at end of file + protected IEnumerable _webSocketConnectionHandler; + protected ISptLogger _logger; + protected JsonUtil _jsonUtil; + + public WebSocketServer( + IEnumerable webSocketConnectionHandlers, + ISptLogger logger, + JsonUtil jsonUtil + ) + { + _webSocketConnectionHandler = webSocketConnectionHandlers; + _logger = logger; + _jsonUtil = jsonUtil; + } + + public Task OnConnection(HttpContext httpContext) + { + return httpContext.WebSockets.AcceptWebSocketAsync() + .ContinueWith(task => HandleCommunication(httpContext, task.Result)); + } + + private void HandleCommunication(HttpContext context, WebSocket webSocket) + { + var socketHandlers = _webSocketConnectionHandler + .Where(wsh => context.Request.Path.Value.Contains(wsh.GetHookUrl())) + .ToList(); + if (socketHandlers.Count == 0) + { + var message = + $"Socket connection received for url {context.Request.Path.Value}, but there is not websocket handler configured for it"; + _logger.Warning(message); + webSocket.SendAsync( + Encoding.UTF8.GetBytes(_jsonUtil.Serialize(new { error = message })), + WebSocketMessageType.Text, + true, + CancellationToken.None + ) + .Wait(); + webSocket.CloseAsync(WebSocketCloseStatus.ProtocolError, message, CancellationToken.None).Wait(); + } + + foreach (var wsh in socketHandlers) + { + wsh.OnConnection(webSocket, context).Wait(); + _logger.Info($"WebSocketHandler \"{wsh.GetSocketId()}\" connected"); + } + } +} diff --git a/Core/Servers/Ws/IWebSocketConnectionHandler.cs b/Core/Servers/Ws/IWebSocketConnectionHandler.cs new file mode 100644 index 00000000..e507af12 --- /dev/null +++ b/Core/Servers/Ws/IWebSocketConnectionHandler.cs @@ -0,0 +1,10 @@ +using System.Net.WebSockets; + +namespace Core.Servers.Ws; + +public interface IWebSocketConnectionHandler +{ + string GetHookUrl(); + string GetSocketId(); + Task OnConnection(WebSocket ws, HttpContext context); +} diff --git a/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs b/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs new file mode 100644 index 00000000..c0d6974b --- /dev/null +++ b/Core/Servers/Ws/Message/DefaultSptWebSocketMessageHandler.cs @@ -0,0 +1,23 @@ +using System.Net.WebSockets; +using System.Text; +using Core.Annotations; + +namespace Core.Servers.Ws.Message; + +[Injectable] +public class DefaultSptWebSocketMessageHandler : 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/Message/ISptWebSocketMessageHandler.cs b/Core/Servers/Ws/Message/ISptWebSocketMessageHandler.cs new file mode 100644 index 00000000..6ca4a2e9 --- /dev/null +++ b/Core/Servers/Ws/Message/ISptWebSocketMessageHandler.cs @@ -0,0 +1,8 @@ +using System.Net.WebSockets; + +namespace Core.Servers.Ws.Message; + +public interface ISptWebSocketMessageHandler +{ + Task OnSptMessage(string sessionID, WebSocket client, byte[] rawData); +} diff --git a/Core/Servers/Ws/SptWebSocketConnectionHandler.cs b/Core/Servers/Ws/SptWebSocketConnectionHandler.cs new file mode 100644 index 00000000..e0c12306 --- /dev/null +++ b/Core/Servers/Ws/SptWebSocketConnectionHandler.cs @@ -0,0 +1,174 @@ +using System.Net.WebSockets; +using System.Text; +using Core.Annotations; +using Core.Helpers; +using Core.Models.Eft.Ws; +using Core.Models.Spt.Config; +using Core.Models.Utils; +using Core.Servers.Ws.Message; +using Core.Services; +using Core.Utils; + +namespace Core.Servers.Ws; + +[Injectable(InjectionType.Singleton)] +public class SptWebSocketConnectionHandler : IWebSocketConnectionHandler +{ + protected Dictionary _sockets = new(); + protected Dictionary _socketAliveTimers = new(); + protected Dictionary _receiveTasks = new(); + protected ISptLogger _logger; + protected LocalisationService _localisationService; + protected JsonUtil _jsonUtil; + protected ProfileHelper _profileHelper; + protected HttpConfig _httpConfig; + protected IEnumerable _messageHandlers; + + 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"; + + public Task OnConnection(WebSocket ws, HttpContext context) + { + var splitUrl = context.Request.Path.Value.Substring(0, context.Request.Path.Value.IndexOf("?")).Split("/"); + var sessionID = splitUrl.First(); + var playerProfile = _profileHelper.GetFullProfile(sessionID); + var playerInfoText = $"{playerProfile.ProfileInfo.Username} ({sessionID})"; + + _logger.Info(_localisationService.GetText("websocket-player_connected", playerInfoText)); + + _sockets.Add(sessionID, ws); + + _socketAliveTimers.Add( + sessionID, + new Timer( + async (_) => + { + _logger.Debug(_localisationService.GetText("websocket-pinging_player", sessionID)); + + if (ws.State == WebSocketState.Open) + { + await ws.SendAsync( + Encoding.UTF8.GetBytes(_jsonUtil.Serialize(_defaultNotification)), + WebSocketMessageType.Text, + true, + CancellationToken.None + ); + } + else + { + _logger.Debug(_localisationService.GetText("websocket-socket_lost_deleting_handle")); + var timer = _socketAliveTimers[sessionID]; + timer.Change(Timeout.Infinite, Timeout.Infinite); + _socketAliveTimers.Remove(sessionID); + _sockets.Remove(sessionID); + var receiveTask = _receiveTasks[sessionID]; + await receiveTask.CancelAsync(); + } + }, + null, + TimeSpan.Zero, + TimeSpan.FromMilliseconds(_httpConfig.WebSocketPingDelayMs) + ) + ); + + _receiveTasks.Add(sessionID, new()); + var cancelToken = _receiveTasks[sessionID].Token; + Task.Factory.StartNew((_) => ReceiveTask(sessionID, ws, cancelToken), null, cancelToken); + + return Task.CompletedTask; + } + + public async Task SendMessageAsync(string sessionID, WsNotificationEvent output) + { + try + { + if (IsWebSocketConnected(sessionID)) + { + var ws = GetSessionWebSocket(sessionID); + + await ws.SendAsync( + Encoding.UTF8.GetBytes(_jsonUtil.Serialize(output)), + WebSocketMessageType.Text, + true, + CancellationToken.None + ); + _logger.Debug(_localisationService.GetText("websocket-message_sent")); + } + else + { + _logger.Debug(_localisationService.GetText("websocket-not_ready_message_not_sent", sessionID)); + } + } + catch (Exception err) + { + _logger.Error(_localisationService.GetText("websocket-message_send_failed_with_error", err)); + } + } + + private void ReceiveTask(string sessionID, WebSocket ws, CancellationToken cancelToken) + { + List readBytes = new(); + while (ws.State == WebSocketState.Open) + { + try + { + if (cancelToken.IsCancellationRequested) + break; + var isEndOfMessage = false; + while (!isEndOfMessage) + { + var buffer = new ArraySegment(new byte[1024 * 4]); + var readTask = ws.ReceiveAsync(buffer, cancelToken); + readTask.Wait(cancelToken); + readBytes.AddRange(buffer); + isEndOfMessage = readTask.Result.EndOfMessage; + } + foreach (var sptWebSocketMessageHandler in _messageHandlers) + { + sptWebSocketMessageHandler.OnSptMessage(sessionID, ws, readBytes.ToArray()).Wait(); + } + } + catch (OperationCanceledException e) + { + _logger.Info("WebSocket disconnecting, receive task finalized..."); + } + catch (Exception e) + { + _logger.Error("Error reading data from WebSocket", e); + } + finally + { + readBytes.Clear(); + } + } + } + + public bool IsWebSocketConnected(string sessionID) + { + return _sockets.TryGetValue(sessionID, out var socket) && socket.State == WebSocketState.Open; + } + + public WebSocket GetSessionWebSocket(string sessionID) + { + return _sockets[sessionID]; + } +} diff --git a/Core/Services/BotEquipmentFilterService.cs b/Core/Services/BotEquipmentFilterService.cs index 8dcd00ee..0d4543c3 100644 --- a/Core/Services/BotEquipmentFilterService.cs +++ b/Core/Services/BotEquipmentFilterService.cs @@ -10,8 +10,8 @@ namespace Core.Services; [Injectable(InjectionType.Singleton)] public class BotEquipmentFilterService { - private readonly ConfigServer _configServer; - private readonly BotConfig _botConfig; + protected ConfigServer _configServer; + protected BotConfig _botConfig; public BotEquipmentFilterService( ConfigServer configServer) diff --git a/Core/Services/BotLootCacheService.cs b/Core/Services/BotLootCacheService.cs index 02dde678..1abb9fe1 100644 --- a/Core/Services/BotLootCacheService.cs +++ b/Core/Services/BotLootCacheService.cs @@ -3,24 +3,25 @@ using Core.Generators; using Core.Helpers; using Core.Models.Eft.Common.Tables; using Core.Models.Spt.Bots; +using Core.Models.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Services; [Injectable(InjectionType.Singleton)] public class BotLootCacheService { - private readonly ILogger _logger; - private readonly ItemHelper _itemHelper; - private readonly PMCLootGenerator _pmcLootGenerator; - private readonly RagfairPriceService _ragfairPriceService; - private readonly ICloner _cloner; + protected ISptLogger _logger; + protected ItemHelper _itemHelper; + protected PMCLootGenerator _pmcLootGenerator; + protected RagfairPriceService _ragfairPriceService; + protected ICloner _cloner; - private readonly Dictionary _lootCache = new(); + protected Dictionary _lootCache = new(); public BotLootCacheService( - ILogger logger, + ISptLogger logger, ItemHelper itemHelper, PMCLootGenerator pmcLootGenerator, RagfairPriceService ragfairPriceService, diff --git a/Core/Services/BotNameService.cs b/Core/Services/BotNameService.cs index 814c243a..7acd24ff 100644 --- a/Core/Services/BotNameService.cs +++ b/Core/Services/BotNameService.cs @@ -4,8 +4,9 @@ using Core.Models.Spt.Bots; using Core.Helpers; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; -using ILogger = Core.Models.Utils.ILogger; + using Core.Utils; namespace Core.Services; @@ -13,18 +14,18 @@ namespace Core.Services; [Injectable(InjectionType.Singleton)] public class BotNameService { - private readonly ILogger _logger; - private readonly BotHelper _botHelper; - private readonly RandomUtil _randomUtil; - private readonly LocalisationService _localisationService; - private readonly DatabaseService _databaseService; - private readonly ConfigServer _configServer; - private readonly BotConfig _botConfig; + protected ISptLogger _logger; + protected BotHelper _botHelper; + protected RandomUtil _randomUtil; + protected LocalisationService _localisationService; + protected DatabaseService _databaseService; + protected ConfigServer _configServer; + protected BotConfig _botConfig; - private readonly HashSet _usedNameCache; + protected HashSet _usedNameCache; public BotNameService( - ILogger logger, + ISptLogger logger, BotHelper botHelper, RandomUtil randomUtil, LocalisationService localisationService, diff --git a/Core/Services/CreateProfileService.cs b/Core/Services/CreateProfileService.cs index 7cbbbc33..5966b6f7 100644 --- a/Core/Services/CreateProfileService.cs +++ b/Core/Services/CreateProfileService.cs @@ -6,35 +6,36 @@ using Core.Models.Eft.Common.Tables; using Core.Models.Eft.ItemEvent; using Core.Models.Eft.Profile; using Core.Models.Enums; +using Core.Models.Utils; using Core.Routers; using Core.Servers; using Core.Utils; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; + namespace Core.Services; [Injectable] public class CreateProfileService { - private readonly ILogger _logger; - private readonly TimeUtil _timeUtil; - private readonly HashUtil _hashUtil; - private readonly DatabaseService _databaseService; - private readonly LocalisationService _localisationService; - private readonly ProfileHelper _profileHelper; - private readonly ItemHelper _itemHelper; - private readonly TraderHelper _traderHelper; - private readonly QuestHelper _questHelper; - private readonly QuestRewardHelper _questRewardHelper; - private readonly ProfileFixerService _profileFixerService; - private readonly SaveServer _saveServer; - private readonly EventOutputHolder _eventOutputHolder; - private readonly PlayerScavGenerator _playerScavGenerator; - private readonly 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( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, HashUtil hashUtil, DatabaseService databaseService, diff --git a/Core/Services/DatabaseService.cs b/Core/Services/DatabaseService.cs index 57349659..1dc68099 100644 --- a/Core/Services/DatabaseService.cs +++ b/Core/Services/DatabaseService.cs @@ -6,10 +6,11 @@ using Core.Models.Spt.Bots; using Core.Models.Spt.Config; using Core.Models.Spt.Server; using Core.Models.Spt.Templates; +using Core.Models.Utils; using Core.Servers; using Core.Utils; using Hideout = Core.Models.Spt.Hideout.Hideout; -using ILogger = Core.Models.Utils.ILogger; + using Locations = Core.Models.Spt.Server.Locations; namespace Core.Services; @@ -20,13 +21,13 @@ public class DatabaseService protected LocationConfig locationConfig; protected bool isDataValid; - private readonly ILogger _logger; - private readonly DatabaseServer _databaseServer; - private readonly LocalisationService _localisationService; - private readonly HashUtil _hashUtil; + protected ISptLogger _logger; + protected DatabaseServer _databaseServer; + protected LocalisationService _localisationService; + protected HashUtil _hashUtil; public DatabaseService( - ILogger logger, + ISptLogger logger, DatabaseServer databaseServer, LocalisationService localisationService, HashUtil hashUtil diff --git a/Core/Services/FenceService.cs b/Core/Services/FenceService.cs index 13c1d3bd..06aedd9e 100644 --- a/Core/Services/FenceService.cs +++ b/Core/Services/FenceService.cs @@ -9,7 +9,7 @@ namespace Core.Services; [Injectable(InjectionType.Singleton)] public class FenceService { - private readonly DatabaseService _databaseService; + protected DatabaseService _databaseService; public FenceService( DatabaseService databaseService) diff --git a/Core/Services/GiftService.cs b/Core/Services/GiftService.cs index 70bae763..ea41672c 100644 --- a/Core/Services/GiftService.cs +++ b/Core/Services/GiftService.cs @@ -3,29 +3,29 @@ using Core.Helpers; using Core.Models.Enums; using Core.Models.Spt.Config; using Core.Models.Spt.Dialog; +using Core.Models.Utils; using Core.Servers; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class GiftService { - private readonly ILogger _logger; + protected ISptLogger _logger; - private readonly MailSendService _mailSendService; - private readonly LocalisationService _localisationService; - private readonly HashUtil _hashUtil; - private readonly TimeUtil _timeUtil; - private readonly ProfileHelper _profileHelper; - private readonly ConfigServer _configServer; + protected MailSendService _mailSendService; + protected LocalisationService _localisationService; + protected HashUtil _hashUtil; + protected TimeUtil _timeUtil; + protected ProfileHelper _profileHelper; + protected ConfigServer _configServer; - private readonly GiftsConfig _giftConfig; + protected GiftsConfig _giftConfig; public GiftService ( - ILogger logger, + ISptLogger logger, MailSendService mailSendService, LocalisationService localisationService, HashUtil hashUtil, diff --git a/Core/Services/ItemFilterService.cs b/Core/Services/ItemFilterService.cs index 6f36841b..620457bc 100644 --- a/Core/Services/ItemFilterService.cs +++ b/Core/Services/ItemFilterService.cs @@ -1,25 +1,25 @@ using Core.Annotations; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Utils.Cloners; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class ItemFilterService { - private readonly ILogger _logger; - private readonly ICloner _cloner; - private readonly DatabaseServer _databaseServer; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected ICloner _cloner; + protected DatabaseServer _databaseServer; + protected ConfigServer _configServer; - private readonly HashSet _lootableItemBlacklistCache = []; - private readonly ItemConfig _itemConfig; + protected HashSet _lootableItemBlacklistCache = []; + protected ItemConfig _itemConfig; public ItemFilterService( - ILogger logger, + ISptLogger logger, ICloner cloner, DatabaseServer databaseServer, ConfigServer configServer diff --git a/Core/Services/LocaleService.cs b/Core/Services/LocaleService.cs index 37d0e770..b102e3ff 100644 --- a/Core/Services/LocaleService.cs +++ b/Core/Services/LocaleService.cs @@ -1,21 +1,20 @@ using System.Globalization; using Core.Annotations; -using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class LocaleService { - private readonly LocaleConfig _localeConfig; - private readonly ILogger _logger; - private readonly DatabaseServer _databaseServer; - private readonly ConfigServer _configServer; + protected LocaleConfig _localeConfig; + protected ISptLogger _logger; + protected DatabaseServer _databaseServer; + protected ConfigServer _configServer; - public LocaleService(ILogger logger, DatabaseServer databaseServer, ConfigServer configServer) + public LocaleService(ISptLogger logger, DatabaseServer databaseServer, ConfigServer configServer) { _logger = logger; _databaseServer = databaseServer; diff --git a/Core/Services/LocalisationService.cs b/Core/Services/LocalisationService.cs index bb664fb3..5519da87 100644 --- a/Core/Services/LocalisationService.cs +++ b/Core/Services/LocalisationService.cs @@ -1,21 +1,21 @@ using Core.Utils; using Core.Annotations; +using Core.Models.Utils; using Core.Servers; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class LocalisationService { - private readonly ILogger _logger; - private readonly RandomUtil _randomUtil; - private readonly DatabaseServer _databaseServer; - private readonly LocaleService _localeService; - private readonly I18nService _i18nService; + protected ISptLogger _logger; + protected RandomUtil _randomUtil; + protected DatabaseServer _databaseServer; + protected LocaleService _localeService; + protected I18nService _i18nService; public LocalisationService( - ILogger logger, + ISptLogger logger, RandomUtil randomUtil, DatabaseServer databaseServer, LocaleService localeService, diff --git a/Core/Services/MailSendService.cs b/Core/Services/MailSendService.cs index 3b9bef99..bcaf354e 100644 --- a/Core/Services/MailSendService.cs +++ b/Core/Services/MailSendService.cs @@ -4,34 +4,34 @@ using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.Spt.Dialog; +using Core.Models.Utils; using Core.Servers; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable] public class MailSendService { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly TimeUtil _timeUtil; - private readonly SaveServer _saveServer; - private readonly DatabaseService _databaseService; - private readonly NotifierHelper _notifierHelper; - private readonly DialogueHelper _dialogueHelper; - private readonly NotificationSendHelper _notificationSendHelper; - private readonly LocalisationService _localisationService; - private readonly ItemHelper _itemHelper; - private readonly 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"; - private readonly List _messageTypes = [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE]; - private readonly List _slotNames = ["hideout", "main"]; + protected List _messageTypes = [MessageType.NPC_TRADER, MessageType.FLEAMARKET_MESSAGE]; + protected List _slotNames = ["hideout", "main"]; public MailSendService ( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, TimeUtil timeUtil, SaveServer saveServer, diff --git a/Core/Services/MapMarkerService.cs b/Core/Services/MapMarkerService.cs index 338781eb..de3b400e 100644 --- a/Core/Services/MapMarkerService.cs +++ b/Core/Services/MapMarkerService.cs @@ -3,22 +3,18 @@ using Core.Annotations; using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Eft.Inventory; -using Core.Models.Eft.Profile; -using Core.Models.Enums; -using Core.Models.Spt.Dialog; -using ILogger = Core.Models.Utils.ILogger; -using MapMarker = Core.Models.Eft.Common.Tables.MapMarker; +using Core.Models.Utils; namespace Core.Services; [Injectable] public class MapMarkerService { - private readonly ILogger _logger; + protected ISptLogger _logger; public MapMarkerService ( - ILogger logger + ISptLogger logger ) { _logger = logger; diff --git a/Core/Services/MatchBotDetailsCacheService.cs b/Core/Services/MatchBotDetailsCacheService.cs index e37988cb..d9e59829 100644 --- a/Core/Services/MatchBotDetailsCacheService.cs +++ b/Core/Services/MatchBotDetailsCacheService.cs @@ -1,21 +1,19 @@ using Core.Annotations; using Core.Models.Eft.Common.Tables; -using Core.Models.Spt.Bots; -using System.Text.RegularExpressions; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; namespace Core.Services { [Injectable(InjectionType.Singleton)] public class MatchBotDetailsCacheService { - private readonly ILogger _logger; - private readonly LocalisationService _localisationService; + protected ISptLogger _logger; + protected LocalisationService _localisationService; - private readonly Dictionary _botDetailsCache; + protected Dictionary _botDetailsCache; public MatchBotDetailsCacheService( - ILogger logger, + ISptLogger logger, LocalisationService localisationService) { _logger = logger; diff --git a/Core/Services/ProfileFixerService.cs b/Core/Services/ProfileFixerService.cs index 570897be..8e48dcaa 100644 --- a/Core/Services/ProfileFixerService.cs +++ b/Core/Services/ProfileFixerService.cs @@ -10,27 +10,27 @@ using Core.Servers; using Core.Utils; using System.Text.RegularExpressions; using Core.Models.Spt.Config; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class ProfileFixerService { - private readonly ILogger _logger; - private readonly HashUtil _hashUtil; - private readonly JsonUtil _jsonUtil; - private readonly ItemHelper _itemHelper; - private readonly QuestRewardHelper _questRewardHelper; - private readonly TraderHelper _traderHelper; - private readonly DatabaseService _databaseService; - private readonly LocalisationService _localisationService; - private readonly ConfigServer _configServer; - private readonly CoreConfig _coreConfig; - private readonly InventoryHelper _inventoryHelper; + protected ISptLogger _logger; + protected HashUtil _hashUtil; + protected JsonUtil _jsonUtil; + protected ItemHelper _itemHelper; + protected QuestRewardHelper _questRewardHelper; + protected TraderHelper _traderHelper; + protected DatabaseService _databaseService; + protected LocalisationService _localisationService; + protected ConfigServer _configServer; + protected CoreConfig _coreConfig; + protected InventoryHelper _inventoryHelper; public ProfileFixerService( - ILogger logger, + ISptLogger logger, HashUtil hashUtil, JsonUtil jsonUtil, ItemHelper itemHelper, @@ -464,7 +464,7 @@ public class ProfileFixerService } } - private readonly List _areas = ["hideout", "main"]; + protected List _areas = ["hideout", "main"]; /** * Checks profile inventory for items that do not exist inside the items db diff --git a/Core/Services/RaidWeatherService.cs b/Core/Services/RaidWeatherService.cs index a1813cee..7ed12662 100644 --- a/Core/Services/RaidWeatherService.cs +++ b/Core/Services/RaidWeatherService.cs @@ -4,29 +4,29 @@ using Core.Helpers; using Core.Models.Eft.Weather; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class RaidWeatherService { - private readonly ILogger _logger; - private readonly DatabaseService _databaseService; - private readonly TimeUtil _timeUtil; - private readonly WeatherGenerator _weatherGenerator; - private readonly SeasonalEventService _seasonalEventService; - private readonly WeightedRandomHelper _weightedRandomHelper; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected DatabaseService _databaseService; + protected TimeUtil _timeUtil; + protected WeatherGenerator _weatherGenerator; + protected SeasonalEventService _seasonalEventService; + protected WeightedRandomHelper _weightedRandomHelper; + protected ConfigServer _configServer; - private readonly List _weatherForecast = []; + protected List _weatherForecast = []; - private readonly WeatherConfig _weatherConfig; + protected WeatherConfig _weatherConfig; public RaidWeatherService( - ILogger logger, + ISptLogger logger, DatabaseService databaseService, TimeUtil timeUtil, WeatherGenerator weatherGenerator, diff --git a/Core/Services/SeasonalEventService.cs b/Core/Services/SeasonalEventService.cs index 51cce4fc..dbfc30fe 100644 --- a/Core/Services/SeasonalEventService.cs +++ b/Core/Services/SeasonalEventService.cs @@ -4,37 +4,37 @@ using Core.Models.Eft.Common; using Core.Models.Eft.Common.Tables; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class SeasonalEventService { - private readonly ILogger _logger; + protected ISptLogger _logger; - private readonly DatabaseService _databaseService; + protected DatabaseService _databaseService; - //private readonly DatabaseImporter _databaseImporter; - private readonly GiftService _giftService; - private readonly LocalisationService _localisationService; - private readonly BotHelper _botHelper; - private readonly ProfileHelper _profileHelper; - private readonly ConfigServer _configServer; + //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; - private readonly SeasonalEventConfig _seasonalEventConfig; - private readonly QuestConfig _questConfig; - private readonly HttpConfig _httpConfig; - private readonly WeatherConfig _weatherConfig; - private readonly LocationConfig _locationConfig; + protected SeasonalEventConfig _seasonalEventConfig; + protected QuestConfig _questConfig; + protected HttpConfig _httpConfig; + protected WeatherConfig _weatherConfig; + protected LocationConfig _locationConfig; private List _currentlyActiveEvents = []; - private readonly IReadOnlyList _christmasEventItems = + protected IReadOnlyList _christmasEventItems = [ ItemTpl.FACECOVER_FAKE_WHITE_BEARD, ItemTpl.BARTER_CHRISTMAS_TREE_ORNAMENT_RED, @@ -48,7 +48,7 @@ public class SeasonalEventService ItemTpl.RANDOMLOOTCONTAINER_NEW_YEAR_GIFT_SMALL ]; - private readonly IReadOnlyList _halloweenEventItems = + protected IReadOnlyList _halloweenEventItems = [ ItemTpl.FACECOVER_SPOOKY_SKULL_MASK, ItemTpl.RANDOMLOOTCONTAINER_PUMPKIN_RAND_LOOT_CONTAINER, @@ -65,7 +65,7 @@ public class SeasonalEventService public SeasonalEventService ( - ILogger logger, + ISptLogger logger, DatabaseService databaseService, //DatabaseImporter databaseImporter, GiftService giftService, diff --git a/Core/Services/TraderPurchasePersisterService.cs b/Core/Services/TraderPurchasePersisterService.cs index f05ad9ce..f33d4866 100644 --- a/Core/Services/TraderPurchasePersisterService.cs +++ b/Core/Services/TraderPurchasePersisterService.cs @@ -3,26 +3,26 @@ using Core.Helpers; using Core.Models.Eft.Profile; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Services; [Injectable(InjectionType.Singleton)] public class TraderPurchasePersisterService { - private readonly ILogger _logger; - private readonly RandomUtil _randomUtil; - private readonly TimeUtil _timeUtil; - private readonly ProfileHelper _profileHelper; - private readonly LocalisationService _localisationService; - private readonly ConfigServer _configServer; + protected ISptLogger _logger; + protected RandomUtil _randomUtil; + protected TimeUtil _timeUtil; + protected ProfileHelper _profileHelper; + protected LocalisationService _localisationService; + protected ConfigServer _configServer; - private readonly TraderConfig _traderConfig; + protected TraderConfig _traderConfig; public TraderPurchasePersisterService( - ILogger logger, + ISptLogger logger, RandomUtil randomUtil, TimeUtil timeUtil, ProfileHelper profileHelper, diff --git a/Core/Utils/App.cs b/Core/Utils/App.cs index 76072328..b6c43582 100644 --- a/Core/Utils/App.cs +++ b/Core/Utils/App.cs @@ -2,9 +2,9 @@ using Core.Annotations; using Core.DI; using Core.Models.Enums; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; -using ILogger = Core.Models.Utils.ILogger; namespace Core.Utils; @@ -14,7 +14,7 @@ public class App protected Dictionary _onUpdateLastRun; protected CoreConfig _coreConfig; - private ILogger _logger; + private ISptLogger _logger; private TimeUtil _timeUtil; private LocalisationService _localisationService; private ConfigServer _configServer; @@ -25,7 +25,7 @@ public class App private IEnumerable _onUpdate; public App( - ILogger logger, + ISptLogger logger, TimeUtil timeUtil, LocalisationService localisationService, ConfigServer configServer, diff --git a/Core/Utils/DatabaseImporter.cs b/Core/Utils/DatabaseImporter.cs index bf7ccce4..69872b4f 100644 --- a/Core/Utils/DatabaseImporter.cs +++ b/Core/Utils/DatabaseImporter.cs @@ -1,14 +1,12 @@ using Core.Annotations; using Core.DI; using Core.Models.Eft.Common.Tables; -using Core.Models.Enums; using Core.Models.Spt.Config; using Core.Models.Spt.Server; +using Core.Models.Utils; using Core.Routers; using Core.Servers; using Core.Services; -using ILogger = Core.Models.Utils.ILogger; -using Path = System.IO.Path; namespace Core.Utils; @@ -20,20 +18,20 @@ public class DatabaseImporter : OnLoad private string filepath; private HttpConfig httpConfig; - private readonly ILogger _logger; - private readonly LocalisationService _localisationService; + protected ISptLogger _logger; + protected LocalisationService _localisationService; - private readonly DatabaseServer _databaseServer; + protected DatabaseServer _databaseServer; - private readonly ImageRouter _imageRouter; - private readonly EncodingUtil _encodingUtil; - private readonly HashUtil _hashUtil; - private readonly ImporterUtil _importerUtil; - private readonly ConfigServer _configServer; - private readonly FileUtil _fileUtil; + protected ImageRouter _imageRouter; + protected EncodingUtil _encodingUtil; + protected HashUtil _hashUtil; + protected ImporterUtil _importerUtil; + protected ConfigServer _configServer; + protected FileUtil _fileUtil; public DatabaseImporter( - ILogger logger, + ISptLogger logger, // TODO: are we gonna use this? @inject("JsonUtil") protected jsonUtil: JsonUtil, FileUtil fileUtil, LocalisationService localisationService, diff --git a/Core/Utils/HashUtil.cs b/Core/Utils/HashUtil.cs index 292fc431..fce527de 100644 --- a/Core/Utils/HashUtil.cs +++ b/Core/Utils/HashUtil.cs @@ -8,9 +8,9 @@ namespace Core.Utils; [Injectable(InjectionType.Singleton)] public class HashUtil { - private readonly Regex MongoIdRegex = new("^[a-fA-F0-9]{24}$"); + protected Regex MongoIdRegex = new("^[a-fA-F0-9]{24}$"); - private readonly RandomUtil _randomUtil; + protected RandomUtil _randomUtil; public HashUtil(RandomUtil randomUtil) { @@ -114,4 +114,4 @@ public enum HashingAlgorithm { MD5, SHA1 -} \ No newline at end of file +} diff --git a/Core/Utils/HttpResponseUtil.cs b/Core/Utils/HttpResponseUtil.cs index 79c439f3..78e08d60 100644 --- a/Core/Utils/HttpResponseUtil.cs +++ b/Core/Utils/HttpResponseUtil.cs @@ -24,7 +24,7 @@ public class HttpResponseUtil _jsonUtil = jsonUtil; } - private readonly ImmutableList _cleanupRegexList = + protected ImmutableList _cleanupRegexList = [ new("[\\b]"), new("[\\f]"), diff --git a/Core/Utils/ImporterUtil.cs b/Core/Utils/ImporterUtil.cs index 86111d44..25b9fa28 100644 --- a/Core/Utils/ImporterUtil.cs +++ b/Core/Utils/ImporterUtil.cs @@ -1,22 +1,19 @@ using System.Reflection; -using System.Text.Json; -using System.Text.Json.Serialization; using Core.Annotations; -using Core.Utils.Json.Converters; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; namespace Core.Utils; [Injectable(InjectionType.Singleton)] public class ImporterUtil { - private readonly FileUtil _fileUtil; - private readonly JsonUtil _jsonUtil; - private readonly Models.Utils.ILogger _logger; + protected FileUtil _fileUtil; + protected JsonUtil _jsonUtil; + protected ISptLogger _logger; - private readonly HashSet filesToIgnore = ["bearsuits.json", "usecsuits.json", "archivedquests.json"]; - - public ImporterUtil(ILogger logger, FileUtil fileUtil, JsonUtil jsonUtil) + protected HashSet filesToIgnore = ["bearsuits.json", "usecsuits.json", "archivedquests.json"]; + + public ImporterUtil(ISptLogger logger, FileUtil fileUtil, JsonUtil jsonUtil) { _logger = logger; _fileUtil = fileUtil; @@ -49,35 +46,41 @@ public class ImporterUtil if (_fileUtil.GetFileExtension(file) != "json") continue; if (filesToIgnore.Contains(_fileUtil.GetFileName(file).ToLower())) continue; tasks.Add( - Task.Factory.StartNew(() => - { - var fileData = _fileUtil.ReadFile(file); - if (onReadCallback != null) - onReadCallback(file, fileData); - - var setMethod = GetSetMethod( - _fileUtil.StripExtension(file).ToLower(), - loadedType, - out var propertyType, - out var isDictionary - ); - try + Task.Factory.StartNew( + () => { - var fileDeserialized = _jsonUtil.Deserialize(fileData, propertyType); - if (onObjectDeserialized != null) - onObjectDeserialized(file, fileDeserialized); + var fileData = _fileUtil.ReadFile(file); + if (onReadCallback != null) + onReadCallback(file, fileData); - lock (dictionaryLock) + var setMethod = GetSetMethod( + _fileUtil.StripExtension(file).ToLower(), + loadedType, + out var propertyType, + out var isDictionary + ); + try { - setMethod.Invoke(result, - isDictionary ? [_fileUtil.StripExtension(file), fileDeserialized] : [fileDeserialized]); + var fileDeserialized = _jsonUtil.Deserialize(fileData, propertyType); + if (onObjectDeserialized != null) + onObjectDeserialized(file, fileDeserialized); + + lock (dictionaryLock) + { + setMethod.Invoke( + result, + isDictionary + ? [_fileUtil.StripExtension(file), fileDeserialized] + : [fileDeserialized] + ); + } + } + catch (Exception e) + { + throw new Exception($"Unable to deserialize or set properties for file '{file}'", e); } } - catch (Exception e) - { - throw new Exception($"Unable to deserialize or set properties for file '{file}'", e); - } - }) + ) ); } @@ -85,33 +88,51 @@ public class ImporterUtil foreach (var directory in directories) { tasks.Add( - Task.Factory.StartNew(() => - { - var setMethod = GetSetMethod(directory.Split("/").Last().Replace("_", ""), loadedType, out var matchedProperty, out var isDictionary); - var loadTask = LoadRecursiveAsync($"{directory}/", matchedProperty); - loadTask.Wait(); - lock (dictionaryLock) + Task.Factory.StartNew( + () => { - setMethod.Invoke(result, isDictionary ? [directory, loadTask.Result] : [loadTask.Result]); + var setMethod = GetSetMethod( + directory.Split("/").Last().Replace("_", ""), + loadedType, + out var matchedProperty, + out var isDictionary + ); + var loadTask = LoadRecursiveAsync($"{directory}/", matchedProperty); + loadTask.Wait(); + lock (dictionaryLock) + { + setMethod.Invoke(result, isDictionary ? [directory, loadTask.Result] : [loadTask.Result]); + } } - }) + ) ); } // return the result of all async fetch - return Task.WhenAll(tasks).ContinueWith((t) => - { - if (t.IsCanceled || t.IsFaulted) - { - var exceptionList = tasks.Where(t => t.IsFaulted || t.IsCanceled).Select(t => t.Exception!).ToList(); - throw new Exception("Error processing one or more DatabaseFiles", new AggregateException(exceptionList)); - } - }).ContinueWith(t => - { - if (t.IsFaulted || t.IsCanceled) - throw t.Exception!; - return result; - }); + return Task.WhenAll(tasks) + .ContinueWith( + (t) => + { + if (t.IsCanceled || t.IsFaulted) + { + var exceptionList = tasks.Where(t => t.IsFaulted || t.IsCanceled) + .Select(t => t.Exception!) + .ToList(); + throw new Exception( + "Error processing one or more DatabaseFiles", + new AggregateException(exceptionList) + ); + } + } + ) + .ContinueWith( + t => + { + if (t.IsFaulted || t.IsCanceled) + throw t.Exception!; + return result; + } + ); } public MethodInfo GetSetMethod(string propertyName, Type type, out Type propertyType, out bool isDictionary) @@ -127,15 +148,22 @@ public class ImporterUtil else { var matchedProperty = type.GetProperties() - .FirstOrDefault(prop => - string.Equals(prop.Name.ToLower(), _fileUtil.StripExtension(propertyName).ToLower(), - StringComparison.Ordinal)); + .FirstOrDefault( + prop => + string.Equals( + prop.Name.ToLower(), + _fileUtil.StripExtension(propertyName).ToLower(), + StringComparison.Ordinal + ) + ); if (matchedProperty == null) throw new Exception( - $"Unable to find property '{_fileUtil.StripExtension(propertyName)}' for type '{type.Name}'"); + $"Unable to find property '{_fileUtil.StripExtension(propertyName)}' for type '{type.Name}'" + ); propertyType = matchedProperty.PropertyType; setMethod = matchedProperty.GetSetMethod(); } + return setMethod; } } diff --git a/Core/Utils/JsonUtil.cs b/Core/Utils/JsonUtil.cs index 96c1786c..21336c6f 100644 --- a/Core/Utils/JsonUtil.cs +++ b/Core/Utils/JsonUtil.cs @@ -3,6 +3,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Unicode; using Core.Annotations; +using Core.Models.Eft.Ws; using Core.Models.Enums; using Core.Models.Spt.Dialog; using Core.Utils.Json.Converters; @@ -29,7 +30,8 @@ public class JsonUtil new EftEnumConverter(), new EftEnumConverter(), new EftEnumConverter(), - new EftEnumConverter() + new EftEnumConverter(), + new EftEnumConverter() } }; private static readonly JsonSerializerOptions jsonSerializerOptionsIndented = new(jsonSerializerOptionsNoIndent) diff --git a/Core/Utils/ProgressWriter.cs b/Core/Utils/ProgressWriter.cs index 068aaa18..d21b47da 100644 --- a/Core/Utils/ProgressWriter.cs +++ b/Core/Utils/ProgressWriter.cs @@ -2,10 +2,10 @@ namespace Core.Utils { public class ProgressWriter { - private readonly int _total; - private readonly int? _maxBarLength; - private readonly string? _barFillChar; - private readonly string? _barEmptyChar; + protected int _total; + protected int? _maxBarLength; + protected string? _barFillChar; + protected string? _barEmptyChar; public ProgressWriter(int total, int maxBarLength, string barFillChar, string barEmptyChar) { diff --git a/Core/Utils/RandomUtil.cs b/Core/Utils/RandomUtil.cs index 106c1671..8479f5d8 100644 --- a/Core/Utils/RandomUtil.cs +++ b/Core/Utils/RandomUtil.cs @@ -1,6 +1,6 @@ using System.Security.Cryptography; using Core.Annotations; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; namespace Core.Utils; @@ -8,11 +8,11 @@ namespace Core.Utils; [Injectable(InjectionType.Singleton)] public class RandomUtil { - private readonly ILogger _logger; + protected ISptLogger _logger; public RandomUtil ( - ILogger logger + ISptLogger logger ) { _logger = logger; diff --git a/Core/Utils/TimerUtil.cs b/Core/Utils/TimerUtil.cs index 76ada3bf..e4c7640c 100644 --- a/Core/Utils/TimerUtil.cs +++ b/Core/Utils/TimerUtil.cs @@ -6,7 +6,7 @@ namespace Core.Utils [Injectable] public class TimerUtil { - private readonly Stopwatch _stopwatch; + protected Stopwatch _stopwatch; public TimerUtil() { diff --git a/Core/Utils/Watermark.cs b/Core/Utils/Watermark.cs index 14d4f52a..20f78039 100644 --- a/Core/Utils/Watermark.cs +++ b/Core/Utils/Watermark.cs @@ -1,7 +1,7 @@ using Core.Annotations; -using Core.Models.Enums; using Core.Models.Logging; using Core.Models.Spt.Config; +using Core.Models.Utils; using Core.Servers; using Core.Services; @@ -51,12 +51,12 @@ public class Watermark { protected List text = []; protected string versionLabel = ""; - protected Models.Utils.ILogger _logger; + protected ISptLogger _logger; protected ConfigServer _configServer; protected LocalisationService _localisationService; protected WatermarkLocale _watermarkLocale; public Watermark( - Models.Utils.ILogger logger, + ISptLogger logger, ConfigServer configServer, LocalisationService localisationService, WatermarkLocale watermarkLocale @@ -182,7 +182,7 @@ public class Watermark { // Log watermark to screen foreach (var text in result) { - _logger.LogWithColor(text, LogTextColor.Yellow); + _logger.LogWithColor(text, textColor: LogTextColor.Yellow); } } } diff --git a/ExampleMods/Mods/Override/WatermarkOverride.cs b/ExampleMods/Mods/Override/WatermarkOverride.cs index 1129726c..f6151ff6 100644 --- a/ExampleMods/Mods/Override/WatermarkOverride.cs +++ b/ExampleMods/Mods/Override/WatermarkOverride.cs @@ -1,8 +1,8 @@ using Core.Annotations; +using Core.Models.Utils; using Core.Servers; using Core.Services; using Core.Utils; -using ILogger = Core.Models.Utils.ILogger; namespace ExampleMods.Mods.Override; @@ -10,7 +10,7 @@ namespace ExampleMods.Mods.Override; public class WatermarkOverride : Watermark { public WatermarkOverride( - ILogger logger, + ISptLogger logger, ConfigServer configServer, LocalisationService localisationService, WatermarkLocale watermarkLocale diff --git a/Server/DependencyInjectionRegistrator.cs b/Server/DependencyInjectionRegistrator.cs new file mode 100644 index 00000000..f7a6e4ba --- /dev/null +++ b/Server/DependencyInjectionRegistrator.cs @@ -0,0 +1,158 @@ +using System.Reflection; +using Core.Annotations; +using Core.Utils; + +namespace Server; + +public static class DependencyInjectionRegistrator +{ + public static void RegisterModOverrideComponents(IServiceCollection builderServices, List assemblies) + { + // We get all the services from this assembly first, since mods will override them later + RegisterComponents( + builderServices, + assemblies.SelectMany(a => a.GetTypes()) + .Where(type => Attribute.IsDefined(type, typeof(Injectable))) + ); + } + + public static void RegisterComponents(IServiceCollection builderServices, IEnumerable types) + { + var groupedTypes = types.SelectMany( + t => + { + var attributes = (Injectable[])Attribute.GetCustomAttributes(t, typeof(Injectable))!; + var registerableType = t; + var registerableComponents = new List(); + foreach (var attribute in attributes) + { + // if we have a type override this takes priority + if (attribute.InjectableTypeOverride != null) + { + registerableType = attribute.InjectableTypeOverride; + } + // if this class only has 1 interface we register it on that interface + else if (registerableType.GetInterfaces().Length == 1) + { + registerableType = registerableType.GetInterfaces()[0]; + } + + registerableComponents.Add(new(registerableType, t, attribute)); + } + + return registerableComponents; + } + ) + .GroupBy(t => t.RegisterableInterface.FullName); + // We get all injectable services to register them on our services + foreach (var groupedInjectables in groupedTypes) + { + foreach (var valueTuple in groupedInjectables.OrderBy(t => t.InjectableAttribute.TypePriority)) + { + if (valueTuple.TypeToRegister.IsGenericType) + RegisterGenericComponents(builderServices, valueTuple); + else + RegisterComponent( + builderServices, + valueTuple.InjectableAttribute.InjectionType, + valueTuple.RegisterableInterface, + valueTuple.TypeToRegister + ); + } + } + } + + private static List AllLoadedTypes; + private static List AllConstructors; + + private static void RegisterGenericComponents(IServiceCollection builderServices, RegisterableType valueTuple) + { + if (AllLoadedTypes == null) + AllLoadedTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).ToList(); + if (AllConstructors == null) + AllConstructors = AllLoadedTypes.SelectMany(t => t.GetConstructors()).ToList(); + var typeName = $"{valueTuple.RegisterableInterface.Namespace}.{valueTuple.RegisterableInterface.Name}"; + try + { + var matchedConstructors = AllConstructors.Where( + c => c.GetParameters() + .Any( + p => p.ParameterType.IsGenericType && + p.ParameterType.GetGenericTypeDefinition().FullName == typeName + ) + ); + + if (matchedConstructors.Any()) + { + foreach (var matchedConstructor in matchedConstructors) + { + foreach (var parameterInfo in matchedConstructor.GetParameters() + .Where( + p => p.ParameterType.IsGenericType && + p.ParameterType.GetGenericTypeDefinition().FullName == typeName + )) + { + var parameters = parameterInfo.ParameterType.GetGenericArguments(); + var typedGeneric = valueTuple.TypeToRegister.MakeGenericType(parameters); + RegisterComponent( + builderServices, + valueTuple.InjectableAttribute.InjectionType, + parameterInfo.ParameterType, + typedGeneric + ); + } + } + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + + private static void RegisterComponent( + IServiceCollection builderServices, + InjectionType injectionType, + Type registerableInterface, + Type imlementationType + ) + { + switch (injectionType) + { + case InjectionType.Singleton: + builderServices.AddSingleton(registerableInterface, imlementationType); + break; + case InjectionType.Transient: + builderServices.AddTransient(registerableInterface, imlementationType); + break; + case InjectionType.Scoped: + builderServices.AddScoped(registerableInterface, imlementationType); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + public static void RegisterSptComponents(IServiceCollection builderServices) + { + // We get all the services from this assembly first, since mods will override them later + RegisterComponents( + builderServices, + typeof(Program).Assembly.GetTypes() + .Where(type => Attribute.IsDefined(type, typeof(Injectable))) + ); + RegisterComponents( + builderServices, + typeof(App).Assembly.GetTypes() + .Where(type => Attribute.IsDefined(type, typeof(Injectable))) + ); + } + + class RegisterableType(Type registerableInterface, Type typeToRegister, Injectable injectableAttribute) + { + public Type RegisterableInterface { get; } = registerableInterface; + public Type TypeToRegister { get; } = typeToRegister; + public Injectable InjectableAttribute { get; } = injectableAttribute; + } +} diff --git a/Server/Logger/AbstractFormatter.cs b/Server/Logger/AbstractFormatter.cs index c231bf5d..6020e908 100644 --- a/Server/Logger/AbstractFormatter.cs +++ b/Server/Logger/AbstractFormatter.cs @@ -6,16 +6,21 @@ namespace Server.Logger; public abstract class AbstractFormatter : ITextFormatter { protected abstract string ProcessText(string text); + + protected virtual string GetFormattedText(string timestamp, string logLevel, string sourceContext, string message) + { + return $"[{timestamp} {logLevel}][{sourceContext}] {message}"; + } public void Format(LogEvent logEvent, TextWriter output) { var newLine = Environment.NewLine; - var timestamp = logEvent.Timestamp.ToString("HH:mm:ss"); + var timestamp = logEvent.Timestamp.ToString("HH:mm:ss.fff"); var logLevel = logEvent.Level.ToString().ToUpper().Substring(0, 4); var message = logEvent.RenderMessage(); var exception = logEvent.Exception != null ? $"{newLine}{logEvent.Exception}{newLine}{logEvent.Exception.StackTrace}" : ""; var sourceContext = logEvent.Properties["SourceContext"].ToString().Replace("\"", ""); - var logMessage = ProcessText($"[{timestamp} {logLevel}][{sourceContext}] {message}{exception}"); + var logMessage = ProcessText(GetFormattedText(timestamp, logLevel, sourceContext, $"{message}{exception}")); output.WriteLine(logMessage); } } diff --git a/Server/Logger/ConsoleFormatter.cs b/Server/Logger/ConsoleFormatter.cs index ab54e092..ceb9ecbe 100644 --- a/Server/Logger/ConsoleFormatter.cs +++ b/Server/Logger/ConsoleFormatter.cs @@ -7,5 +7,10 @@ public class ConsoleFormatter : AbstractFormatter return text; } - public static ConsoleFormatter Default { get; } = new ConsoleFormatter(); + protected override string GetFormattedText(string timestamp, string logLevel, string sourceContext, string message) + { + return message; + } + + public static ConsoleFormatter Default { get; } = new(); } diff --git a/Server/Logger/WebApplicationLogger.cs b/Server/Logger/WebApplicationLogger.cs index 374b70ab..b760359a 100644 --- a/Server/Logger/WebApplicationLogger.cs +++ b/Server/Logger/WebApplicationLogger.cs @@ -1,69 +1,79 @@ using Core.Annotations; using Core.Models.Logging; -using ILogger = Core.Models.Utils.ILogger; +using Core.Models.Utils; namespace Server.Logger; [Injectable] -public class WebApplicationLogger : ILogger +public class SptWebApplicationLogger : ISptLogger { - private Microsoft.Extensions.Logging.ILogger _logger; - public WebApplicationLogger(ILoggerProvider provider) + private ILogger _logger; + + public SptWebApplicationLogger(ILoggerProvider provider) { - _logger = provider.CreateLogger("SptLogger"); + _logger = provider.CreateLogger(typeof(T).FullName); } - public void LogWithColor(string data, LogTextColor? textColor = null, LogBackgroundColor? backgroundColor = null) + public void LogWithColor( + string data, + Exception? ex = null, + LogTextColor? textColor = null, + LogBackgroundColor? backgroundColor = null + ) { if (textColor != null || backgroundColor != null) { - _logger.LogInformation(GetColorizedText(data, textColor, backgroundColor)); + _logger.LogInformation(ex, GetColorizedText(data, textColor, backgroundColor)); } - else - _logger.LogInformation(data); + else + _logger.LogInformation(ex, data); } - private string GetColorizedText(string data, LogTextColor? textColor = null, LogBackgroundColor? backgroundColor = null) + private string GetColorizedText( + string data, + LogTextColor? textColor = null, + LogBackgroundColor? backgroundColor = null + ) { var colorString = string.Empty; if (textColor != null) colorString += ((int)textColor.Value).ToString(); - + if (backgroundColor != null) colorString += string.IsNullOrEmpty(colorString) ? ((int)backgroundColor.Value).ToString() : $";{((int)backgroundColor.Value).ToString()}"; - + return $"\x1b[{colorString}m{data}\x1b[0m"; } - public void Success(string data) + public void Success(string data, Exception? ex = null) { - _logger.LogInformation(GetColorizedText(data, LogTextColor.Green)); + _logger.LogInformation(ex, GetColorizedText(data, LogTextColor.Green)); } - public void Error(string data) + public void Error(string data, Exception? ex = null) { - _logger.LogError(GetColorizedText(data, LogTextColor.Red)); + _logger.LogError(ex, GetColorizedText(data, LogTextColor.Red)); } - public void Warning(string data) + public void Warning(string data, Exception? ex = null) { - _logger.LogWarning(GetColorizedText(data, LogTextColor.Yellow)); - } - - public void Info(string data) - { - _logger.LogInformation(data); + _logger.LogWarning(ex, GetColorizedText(data, LogTextColor.Yellow)); } - public void Debug(string data) + public void Info(string data, Exception? ex = null) { - _logger.LogDebug(data); + _logger.LogInformation(ex, data); } - public void Critical(string data) + public void Debug(string data, Exception? ex = null) { - _logger.LogCritical(GetColorizedText(data, LogTextColor.Black, LogBackgroundColor.Red)); + _logger.LogDebug(ex, data); + } + + public void Critical(string data, Exception? ex = null) + { + _logger.LogCritical(ex, GetColorizedText(data, LogTextColor.Black, LogBackgroundColor.Red)); } } diff --git a/Server/Program.cs b/Server/Program.cs index 468e87f3..649a9356 100644 --- a/Server/Program.cs +++ b/Server/Program.cs @@ -27,8 +27,8 @@ public static class Program ProgramStatics.Initialize(); - RegisterSptComponents(builder.Services); - RegisterModOverrideComponents(builder.Services, assemblies); + DependencyInjectionRegistrator.RegisterSptComponents(builder.Services); + DependencyInjectionRegistrator.RegisterModOverrideComponents(builder.Services, assemblies); ILogger logger = new SerilogLoggerProvider(registeredLogger).CreateLogger("Server"); try { @@ -64,8 +64,8 @@ public static class Program // throw ex; } } - - private static void CreateAndRegisterLogger(WebApplicationBuilder builder, out Serilog.Core.Logger logger) + + public static void CreateAndRegisterLogger(WebApplicationBuilder builder, out Serilog.Core.Logger logger) { builder.Logging.ClearProviders(); logger = new LoggerConfiguration() @@ -77,73 +77,4 @@ public static class Program .CreateLogger(); builder.Logging.AddSerilog(logger); } - - private static void RegisterModOverrideComponents(IServiceCollection builderServices, List assemblies) - { - // We get all the services from this assembly first, since mods will override them later - RegisterComponents(builderServices, assemblies.SelectMany(a => a.GetTypes()) - .Where(type => Attribute.IsDefined(type, typeof(Injectable)))); - } - - private static void RegisterComponents(IServiceCollection builderServices, IEnumerable types) - { - var groupedTypes = types.SelectMany(t => - { - var attributes = (Injectable[]) Attribute.GetCustomAttributes(t, typeof(Injectable))!; - var registerableType = t; - var registerableComponents = new List(); - foreach (var attribute in attributes) - { - // if we have a type override this takes priority - if (attribute.InjectableTypeOverride != null) - { - registerableType = attribute.InjectableTypeOverride; - } - // if this class only has 1 interface we register it on that interface - else if (registerableType.GetInterfaces().Length == 1) - { - registerableType = registerableType.GetInterfaces()[0]; - } - registerableComponents.Add(new(registerableType, t, attribute)); - } - return registerableComponents; - }).GroupBy(t => t.RegisterableInterface.FullName); - // We get all injectable services to register them on our services - foreach (var groupedInjectables in groupedTypes) - { - foreach (var valueTuple in groupedInjectables.OrderBy(t => t.InjectableAttribute.TypePriority)) - { - switch (valueTuple.InjectableAttribute.InjectionType) - { - case InjectionType.Singleton: - builderServices.AddSingleton(valueTuple.RegisterableInterface, valueTuple.TypeToRegister); - break; - case InjectionType.Transient: - builderServices.AddTransient(valueTuple.RegisterableInterface, valueTuple.TypeToRegister); - break; - case InjectionType.Scoped: - builderServices.AddScoped(valueTuple.RegisterableInterface, valueTuple.TypeToRegister); - break; - default: - throw new ArgumentOutOfRangeException(); - } - } - } - } - - private static void RegisterSptComponents(IServiceCollection builderServices) - { - // We get all the services from this assembly first, since mods will override them later - RegisterComponents(builderServices, typeof(Program).Assembly.GetTypes() - .Where(type => Attribute.IsDefined(type, typeof(Injectable)))); - RegisterComponents(builderServices, typeof(App).Assembly.GetTypes() - .Where(type => Attribute.IsDefined(type, typeof(Injectable)))); - } - - class RegisterableType(Type registerableInterface, Type typeToRegister, Injectable injectableAttribute) - { - public Type RegisterableInterface { get; } = registerableInterface; - public Type TypeToRegister { get; } = typeToRegister; - public Injectable InjectableAttribute { get; } = injectableAttribute; - } } diff --git a/Server/Server.csproj b/Server/Server.csproj index 56863876..899454fc 100644 --- a/Server/Server.csproj +++ b/Server/Server.csproj @@ -36,4 +36,8 @@ + + + + diff --git a/Server/user/mods/TestMod/ExampleOverrideMod.dll b/Server/user/mods/TestMod/ExampleOverrideMod.dll deleted file mode 100644 index 9b58eb5f..00000000 Binary files a/Server/user/mods/TestMod/ExampleOverrideMod.dll and /dev/null differ diff --git a/UnitTests/Tests/Utils/HashUtilTests.cs b/UnitTests/Tests/Utils/HashUtilTests.cs index f6550a5a..f23023a1 100644 --- a/UnitTests/Tests/Utils/HashUtilTests.cs +++ b/UnitTests/Tests/Utils/HashUtilTests.cs @@ -5,7 +5,7 @@ namespace UnitTests.Tests.Utils; [TestClass] public class HashUtilTests { - // private readonly HashUtil _hashUtil = new(new RandomUtil()); + // protected HashUtil _hashUtil = new(new RandomUtil()); // // [TestMethod] // public void GenerateTest() diff --git a/UnitTests/Tests/Utils/JsonUtilTests.cs b/UnitTests/Tests/Utils/JsonUtilTests.cs index f7d768e3..0c50a426 100644 --- a/UnitTests/Tests/Utils/JsonUtilTests.cs +++ b/UnitTests/Tests/Utils/JsonUtilTests.cs @@ -6,7 +6,7 @@ namespace UnitTests.Tests.Utils; [TestClass] public class JsonUtilTests { - private readonly JsonUtil _jsonUtil = new(); + protected JsonUtil _jsonUtil = new(); [TestMethod] public void SerializeAndDeserialize_WithDictionaryOfETFEnum_ExpectCorrectParsing() { diff --git a/UnitTests/Tests/Utils/MathUtilTests.cs b/UnitTests/Tests/Utils/MathUtilTests.cs index 79400d7f..db742456 100644 --- a/UnitTests/Tests/Utils/MathUtilTests.cs +++ b/UnitTests/Tests/Utils/MathUtilTests.cs @@ -5,7 +5,7 @@ namespace UnitTests.Tests.Utils; [TestClass] public class MathUtilTests { - private readonly MathUtil _mathUtil = new(); + protected MathUtil _mathUtil = new(); [TestMethod] public void ListSumTest() @@ -80,4 +80,4 @@ public class MathUtilTests Assert.AreEqual(expected, actual, $"MapToRange() Expected: {expected}, Actual: {actual}"); } -} \ No newline at end of file +} diff --git a/UnitTests/Tests/Utils/RandomUtilTests.cs b/UnitTests/Tests/Utils/RandomUtilTests.cs index 9e18760a..9aa8f9b9 100644 --- a/UnitTests/Tests/Utils/RandomUtilTests.cs +++ b/UnitTests/Tests/Utils/RandomUtilTests.cs @@ -5,7 +5,7 @@ namespace UnitTests.Tests.Utils; [TestClass] public sealed class RandomUtilTests { - // private readonly RandomUtil _randomUtil = new(); + // protected RandomUtil _randomUtil = new(); // // [TestMethod] // public void GetIntTest() diff --git a/server-csharp.sln.DotSettings b/server-csharp.sln.DotSettings index 520e5053..a385c652 100644 --- a/server-csharp.sln.DotSettings +++ b/server-csharp.sln.DotSettings @@ -1,8 +1,17 @@  True + 10000 NEVER NEVER NEVER + True + CHOP_IF_LONG + CHOP_IF_LONG + True + CHOP_IF_LONG + CHOP_IF_LONG + CHOP_IF_LONG + CHOP_IF_LONG True True True