diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/CustomizationCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/CustomizationCallbacks.cs index 09f94c3e..cf39e33c 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/CustomizationCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/CustomizationCallbacks.cs @@ -11,9 +11,9 @@ namespace SPTarkov.Server.Core.Callbacks; [Injectable] public class CustomizationCallbacks( - CustomizationController _customizationController, - SaveServer _saveServer, - HttpResponseUtil _httpResponseUtil + CustomizationController customizationController, + SaveServer saveServer, + HttpResponseUtil httpResponseUtil ) { /// @@ -27,7 +27,7 @@ public class CustomizationCallbacks( ) { return new ValueTask( - _httpResponseUtil.GetBody(_saveServer.GetProfile(sessionID).CustomisationUnlocks) + httpResponseUtil.GetBody(saveServer.GetProfile(sessionID).CustomisationUnlocks) ); } @@ -41,7 +41,7 @@ public class CustomizationCallbacks( var traderId = splitUrl[^3]; return new ValueTask( - _httpResponseUtil.GetBody(_customizationController.GetTraderSuits(traderId, sessionID)) + httpResponseUtil.GetBody(customizationController.GetTraderSuits(traderId, sessionID)) ); } @@ -55,7 +55,7 @@ public class CustomizationCallbacks( MongoId sessionID ) { - return _customizationController.BuyCustomisation(pmcData, request, sessionID); + return customizationController.BuyCustomisation(pmcData, request, sessionID); } /// @@ -69,7 +69,7 @@ public class CustomizationCallbacks( ) { return new ValueTask( - _httpResponseUtil.GetBody(_customizationController.GetHideoutCustomisation(sessionID)) + httpResponseUtil.GetBody(customizationController.GetHideoutCustomisation(sessionID)) ); } @@ -80,7 +80,7 @@ public class CustomizationCallbacks( public ValueTask GetStorage(string url, EmptyRequestData _, MongoId sessionID) { return new ValueTask( - _httpResponseUtil.GetBody(_customizationController.GetCustomisationStorage(sessionID)) + httpResponseUtil.GetBody(customizationController.GetCustomisationStorage(sessionID)) ); } @@ -94,6 +94,6 @@ public class CustomizationCallbacks( MongoId sessionID ) { - return _customizationController.SetCustomisation(sessionID, request, pmcData); + return customizationController.SetCustomisation(sessionID, request, pmcData); } } diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/LauncherCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/LauncherCallbacks.cs index d5569760..cb322aa3 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/LauncherCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/LauncherCallbacks.cs @@ -24,7 +24,7 @@ public class LauncherCallbacks( public ValueTask Login(string url, LoginRequestData info, MongoId sessionID) { var output = launcherController.Login(info); - return new ValueTask(output ?? "FAILED"); + return new ValueTask(output.IsEmpty() ? "FAILED" : output); } public async ValueTask Register(string url, RegisterData info, MongoId sessionID) @@ -54,7 +54,7 @@ public class LauncherCallbacks( public ValueTask Wipe(string url, RegisterData info, MongoId sessionID) { var output = launcherController.Wipe(info); - return new ValueTask(string.IsNullOrEmpty(output) ? "FAILED" : "OK"); + return new ValueTask(output.IsEmpty() ? "FAILED" : "OK"); } public ValueTask GetServerVersion() diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/LauncherV2Callbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/LauncherV2Callbacks.cs index b13dbc6c..f287240d 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/LauncherV2Callbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/LauncherV2Callbacks.cs @@ -110,7 +110,7 @@ public class LauncherV2Callbacks( ); } - public ValueTask Profile(MongoId? sessionId) + public ValueTask Profile(MongoId sessionId) { return new ValueTask( httpResponseUtil.NoBody( diff --git a/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs b/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs index 87fc091b..1409fd26 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs @@ -14,13 +14,13 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class BuildController( - ISptLogger _logger, - DatabaseService _databaseService, - ProfileHelper _profileHelper, - ServerLocalisationService _serverLocalisationService, - ItemHelper _itemHelper, - SaveServer _saveServer, - ICloner _cloner + ISptLogger logger, + DatabaseService databaseService, + ProfileHelper profileHelper, + ServerLocalisationService serverLocalisationService, + ItemHelper itemHelper, + SaveServer saveServer, + ICloner cloner ) { /// @@ -32,7 +32,7 @@ public class BuildController( { const string secureContainerSlotId = "SecuredContainer"; - var profile = _profileHelper.GetFullProfile(sessionID); + var profile = profileHelper.GetFullProfile(sessionID); if (profile?.UserBuildData is null) { profile.UserBuildData = new UserBuilds @@ -44,8 +44,8 @@ public class BuildController( } // Ensure the secure container in the default presets match what the player has equipped - var defaultEquipmentPresetsClone = _cloner - .Clone(_databaseService.GetTemplates().DefaultEquipmentPresets) + var defaultEquipmentPresetsClone = cloner + .Clone(databaseService.GetTemplates().DefaultEquipmentPresets) .ToList(); // Get players secure container @@ -78,7 +78,7 @@ public class BuildController( } // Clone player build data from profile and append the above defaults onto end - var userBuildsClone = _cloner.Clone(profile?.UserBuildData); + var userBuildsClone = cloner.Clone(profile?.UserBuildData); userBuildsClone.EquipmentBuilds ??= []; userBuildsClone?.EquipmentBuilds?.AddRange(defaultEquipmentPresetsClone); @@ -93,11 +93,11 @@ public class BuildController( /// public void SaveWeaponBuild(MongoId sessionId, PresetBuildActionRequestData body) { - var pmcData = _profileHelper.GetPmcProfile(sessionId); + var pmcData = profileHelper.GetPmcProfile(sessionId); // Replace duplicate Id's. The first item is the base item. // The root ID and the base item ID need to match. - body.Items = _itemHelper.ReplaceIDs(body.Items, pmcData); + body.Items = itemHelper.ReplaceIDs(body.Items, pmcData); body.Root = body.Items.FirstOrDefault().Id; // Create new object ready to save into profile userbuilds.weaponBuilds @@ -109,7 +109,7 @@ public class BuildController( Items = body.Items, }; - var profile = _profileHelper.GetFullProfile(sessionId); + var profile = profileHelper.GetFullProfile(sessionId); var savedWeaponBuilds = profile.UserBuildData.WeaponBuilds; var existingBuild = savedWeaponBuilds.FirstOrDefault(x => x.Id == body.Id); @@ -133,16 +133,16 @@ public class BuildController( /// public void SaveEquipmentBuild(MongoId sessionID, PresetBuildActionRequestData request) { - var profile = _profileHelper.GetFullProfile(sessionID); + var profile = profileHelper.GetFullProfile(sessionID); var pmcData = profile.CharacterData.PmcData; - var existingSavedEquipmentBuilds = _saveServer + var existingSavedEquipmentBuilds = saveServer .GetProfile(sessionID) .UserBuildData.EquipmentBuilds; // Replace duplicate ID's. The first item is the base item. // Root ID and the base item ID need to match. - request.Items = _itemHelper.ReplaceIDs(request.Items, pmcData); + request.Items = itemHelper.ReplaceIDs(request.Items, pmcData); var newBuild = new EquipmentBuild { @@ -199,7 +199,7 @@ public class BuildController( Items = request.Items, }; - var profile = _profileHelper.GetFullProfile(sessionId); + var profile = profileHelper.GetFullProfile(sessionId); profile.UserBuildData.MagazineBuilds ??= []; @@ -224,7 +224,7 @@ public class BuildController( /// Session/Player id protected void RemovePlayerBuild(string idToRemove, MongoId sessionID) { - var profile = _saveServer.GetProfile(sessionID); + var profile = saveServer.GetProfile(sessionID); var weaponBuilds = profile.UserBuildData.WeaponBuilds; var equipmentBuilds = profile.UserBuildData.EquipmentBuilds; var magazineBuilds = profile.UserBuildData.MagazineBuilds; @@ -263,8 +263,8 @@ public class BuildController( } // Not found in weapons,equipment or magazines, not good - _logger.Error( - _serverLocalisationService.GetText("build-unable_to_delete_preset", idToRemove) + logger.Error( + serverLocalisationService.GetText("build-unable_to_delete_preset", idToRemove) ); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/ClientLogController.cs b/Libraries/SPTarkov.Server.Core/Controllers/ClientLogController.cs index 5f78ba6e..ac01a51e 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/ClientLogController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/ClientLogController.cs @@ -7,7 +7,7 @@ using LogLevel = SPTarkov.Server.Core.Models.Spt.Logging.LogLevel; namespace SPTarkov.Server.Core.Controllers; [Injectable] -public class ClientLogController(ISptLogger _logger) +public class ClientLogController(ISptLogger logger) { /// /// Handle /singleplayer/log @@ -20,6 +20,6 @@ public class ClientLogController(ISptLogger _logger) var color = logRequest.Color ?? LogTextColor.White; var backgroundColor = logRequest.BackgroundColor ?? LogBackgroundColor.Default; - _logger.Log(logRequest.Level ?? LogLevel.Info, message, color, backgroundColor); + logger.Log(logRequest.Level ?? LogLevel.Info, message, color, backgroundColor); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs b/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs index 754f92da..d55f39c7 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs @@ -18,14 +18,14 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class CustomizationController( - ISptLogger _logger, - EventOutputHolder _eventOutputHolder, - DatabaseService _databaseService, - SaveServer _saveServer, - ServerLocalisationService _serverLocalisationService, - ProfileHelper _profileHelper, - ICloner _cloner, - PaymentService _paymentService + ISptLogger logger, + EventOutputHolder eventOutputHolder, + DatabaseService databaseService, + SaveServer saveServer, + ServerLocalisationService serverLocalisationService, + ProfileHelper profileHelper, + ICloner cloner, + PaymentService paymentService ) { /// @@ -36,9 +36,9 @@ public class CustomizationController( /// Suit array public List GetTraderSuits(string traderId, MongoId sessionId) { - var pmcData = _profileHelper.GetPmcProfile(sessionId); - var clothing = _databaseService.GetCustomization(); - var suits = _databaseService.GetTrader(traderId).Suits; + var pmcData = profileHelper.GetPmcProfile(sessionId); + var clothing = databaseService.GetCustomization(); + var suits = databaseService.GetTrader(traderId).Suits; var matchingSuits = suits?.Where(s => clothing.ContainsKey(s.SuiteId!)).ToList(); matchingSuits = matchingSuits @@ -51,7 +51,7 @@ public class CustomizationController( if (matchingSuits == null) { throw new Exception( - _serverLocalisationService.GetText( + serverLocalisationService.GetText( "customisation-unable_to_get_trader_suits", traderId ) @@ -75,13 +75,13 @@ public class CustomizationController( MongoId sessionId ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); var traderOffer = GetTraderClothingOffer(sessionId, buyClothingRequest.Offer); if (traderOffer is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "customisation-unable_to_find_suit_by_id", buyClothingRequest.Offer ) @@ -92,9 +92,9 @@ public class CustomizationController( var suitId = traderOffer.SuiteId; if (OutfitAlreadyPurchased(suitId ?? string.Empty, sessionId)) { - var suitDetails = _databaseService.GetCustomization()!.GetValueOrDefault(suitId); - _logger.Error( - _serverLocalisationService.GetText( + var suitDetails = databaseService.GetCustomization()!.GetValueOrDefault(suitId); + logger.Error( + serverLocalisationService.GetText( "customisation-item_already_purchased", new { itemId = suitDetails?.Id, itemName = suitDetails?.Name } ) @@ -106,7 +106,7 @@ public class CustomizationController( // Charge player for buying item PayForClothingItems(sessionId, pmcData, buyClothingRequest.Items, output); - var profile = _saveServer.GetProfile(sessionId); + var profile = saveServer.GetProfile(sessionId); // TODO: Merge with function _profileHelper.addHideoutCustomisationUnlock var rewardToStore = new CustomisationStorage @@ -129,7 +129,7 @@ public class CustomizationController( /// true if already purchased protected bool OutfitAlreadyPurchased(object suitId, MongoId sessionId) { - var fullProfile = _profileHelper.GetFullProfile(sessionId); + var fullProfile = profileHelper.GetFullProfile(sessionId); // Check if clothing can be found by id return fullProfile.CustomisationUnlocks.Exists(customisation => @@ -148,8 +148,8 @@ public class CustomizationController( var foundSuit = GetAllTraderSuits(sessionId).FirstOrDefault(s => s.Id == offerId); if (foundSuit is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "customisation-unable_to_find_suit_with_id", offerId ) @@ -198,7 +198,7 @@ public class CustomizationController( SchemeId = 0, }; - _paymentService.PayMoney(pmcData, options, sessionId, output); + paymentService.PayMoney(pmcData, options, sessionId, output); } } @@ -209,7 +209,7 @@ public class CustomizationController( /// protected List GetAllTraderSuits(MongoId sessionId) { - var traders = _databaseService.GetTraders(); + var traders = databaseService.GetTraders(); var result = new List(); foreach (var (traderId, trader) in traders) @@ -233,7 +233,7 @@ public class CustomizationController( /// public HideoutCustomisation GetHideoutCustomisation(MongoId sessionId) { - return _databaseService.GetHideout().Customisation!; + return databaseService.GetHideout().Customisation!; } /// @@ -243,11 +243,11 @@ public class CustomizationController( /// public List GetCustomisationStorage(MongoId sessionId) { - var customisationResultsClone = _cloner.Clone( - _databaseService.GetTemplates().CustomisationStorage + var customisationResultsClone = cloner.Clone( + databaseService.GetTemplates().CustomisationStorage ); - var profile = _profileHelper.GetFullProfile(sessionId); + var profile = profileHelper.GetFullProfile(sessionId); if (profile is null) { return customisationResultsClone!; @@ -282,12 +282,12 @@ public class CustomizationController( ApplyClothingItemToProfile(customisation, pmcData); break; default: - _logger.Error($"Unhandled customisation type: {customisation.Type}"); + logger.Error($"Unhandled customisation type: {customisation.Type}"); break; } } - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -297,11 +297,11 @@ public class CustomizationController( /// Profile to update protected void ApplyClothingItemToProfile(CustomizationSetOption customisation, PmcData pmcData) { - var dbSuit = _databaseService.GetCustomization()[customisation.Id!]; + var dbSuit = databaseService.GetCustomization()[customisation.Id!]; if (dbSuit is null) { - _logger.Error( + logger.Error( $"Unable to find suit customisation id: {customisation.Id}, cannot apply clothing to player profile: {pmcData.Id}" ); return; diff --git a/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs b/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs index 56a3c4f2..30b37e87 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs @@ -16,19 +16,19 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class DialogueController( - ISptLogger _logger, - TimeUtil _timeUtil, - DialogueHelper _dialogueHelper, - NotificationSendHelper _notificationSendHelper, - ProfileHelper _profileHelper, - ConfigServer _configServer, - SaveServer _saveServer, - ServerLocalisationService _serverLocalisationService, - MailSendService _mailSendService, + ISptLogger logger, + TimeUtil timeUtil, + DialogueHelper dialogueHelper, + NotificationSendHelper notificationSendHelper, + ProfileHelper profileHelper, + ConfigServer configServer, + SaveServer saveServer, + ServerLocalisationService serverLocalisationService, + MailSendService mailSendService, IEnumerable dialogueChatBots ) { - protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly CoreConfig _coreConfig = configServer.GetConfig(); protected readonly List _dialogueChatBots = dialogueChatBots.ToList(); /// @@ -38,8 +38,8 @@ public class DialogueController( { if (_dialogueChatBots.Any(cb => cb.GetChatBot().Id == chatBot.GetChatBot().Id)) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "dialog-chatbot_id_already_exists", chatBot.GetChatBot().Id ) @@ -54,7 +54,7 @@ public class DialogueController( /// public void Update() { - var profiles = _saveServer.GetProfiles(); + var profiles = saveServer.GetProfiles(); foreach (var kvp in profiles) { RemoveExpiredItemsFromMessages(kvp.Key); @@ -72,12 +72,12 @@ public class DialogueController( var friends = GetActiveChatBots(); // Add any friends the user has after the chatbots - var profile = _profileHelper.GetFullProfile(sessionId); + var profile = profileHelper.GetFullProfile(sessionId); if (profile?.FriendProfileIds is not null) { foreach (var friendId in profile.FriendProfileIds) { - var friendProfile = _profileHelper.GetChatRoomMemberFromSessionId(friendId); + var friendProfile = profileHelper.GetChatRoomMemberFromSessionId(friendId); if (friendProfile is not null) { friends.Add( @@ -128,7 +128,7 @@ public class DialogueController( public virtual List GenerateDialogueList(MongoId sessionId) { var data = new List(); - foreach (var (_, dialog) in _dialogueHelper.GetDialogsForProfile(sessionId)) + foreach (var (_, dialog) in dialogueHelper.GetDialogsForProfile(sessionId)) { var dialogueInfo = GetDialogueInfo(dialog, sessionId); if (dialogueInfo is null) @@ -150,7 +150,7 @@ public class DialogueController( /// DialogueInfo public virtual DialogueInfo? GetDialogueInfo(string? dialogueId, MongoId sessionId) { - var dialogs = _dialogueHelper.GetDialogsForProfile(sessionId); + var dialogs = dialogueHelper.GetDialogsForProfile(sessionId); var dialogue = dialogs!.GetValueOrDefault(dialogueId); return GetDialogueInfo(dialogue, sessionId); @@ -173,7 +173,7 @@ public class DialogueController( { Id = dialogue.Id, Type = dialogue?.Type ?? MessageType.NpcTraderMessage, - Message = _dialogueHelper.GetMessagePreview(dialogue), + Message = dialogueHelper.GetMessagePreview(dialogue), New = dialogue?.New, AttachmentsNew = dialogue?.AttachmentsNew, Pinned = dialogue?.Pinned, @@ -196,7 +196,7 @@ public class DialogueController( MongoId sessionId ) { - var profile = _saveServer.GetProfile(sessionId); + var profile = saveServer.GetProfile(sessionId); // User to user messages are special in that they need the player to exist in them, add if they don't if ( @@ -246,7 +246,7 @@ public class DialogueController( ) { var dialogueId = request.DialogId; - var fullProfile = _saveServer.GetProfile(sessionId); + var fullProfile = saveServer.GetProfile(sessionId); var dialogue = GetDialogByIdFromProfile(fullProfile, request); if (!dialogue.Messages.Any()) @@ -403,8 +403,8 @@ public class DialogueController( /// Message array protected List GetActiveMessagesFromDialog(MongoId sessionId, string dialogueId) { - var timeNow = _timeUtil.GetTimeStamp(); - var dialogs = _dialogueHelper.GetDialogsForProfile(sessionId); + var timeNow = timeUtil.GetTimeStamp(); + var dialogs = dialogueHelper.GetDialogsForProfile(sessionId); return dialogs[dialogueId] .Messages?.Where(message => @@ -433,11 +433,11 @@ public class DialogueController( /// Player id public virtual void RemoveDialogue(string? dialogueId, MongoId sessionId) { - var profile = _saveServer.GetProfile(sessionId); + var profile = saveServer.GetProfile(sessionId); if (!profile.DialogueRecords.ContainsKey(dialogueId)) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "dialogue-unable_to_find_in_profile", new { sessionId, dialogueId } ) @@ -457,11 +457,11 @@ public class DialogueController( /// Session/Player id public virtual void SetDialoguePin(string? dialogueId, bool shouldPin, MongoId sessionId) { - var dialog = _dialogueHelper.GetDialogsForProfile(sessionId).GetValueOrDefault(dialogueId); + var dialog = dialogueHelper.GetDialogsForProfile(sessionId).GetValueOrDefault(dialogueId); if (dialog is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "dialogue-unable_to_find_in_profile", new { sessionId, dialogueId } ) @@ -481,11 +481,11 @@ public class DialogueController( /// Player profile id public virtual void SetRead(List? dialogueIds, MongoId sessionId) { - var dialogs = _dialogueHelper.GetDialogsForProfile(sessionId); + var dialogs = dialogueHelper.GetDialogsForProfile(sessionId); if (dialogs?.Any() != true) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "dialogue-unable_to_find_dialogs_in_profile", new { sessionId } ) @@ -513,11 +513,11 @@ public class DialogueController( MongoId sessionId ) { - var dialogs = _dialogueHelper.GetDialogsForProfile(sessionId); + var dialogs = dialogueHelper.GetDialogsForProfile(sessionId); var dialog = dialogs.TryGetValue(dialogueId, out var dialogInfo); if (!dialog) { - _logger.Error(_serverLocalisationService.GetText("dialogue-unable_to_find_in_profile")); + logger.Error(serverLocalisationService.GetText("dialogue-unable_to_find_in_profile")); return null; } @@ -547,7 +547,7 @@ public class DialogueController( SendMessageRequest request ) { - _mailSendService.SendPlayerMessageToNpc(sessionId, request.DialogId!, request.Text!); + mailSendService.SendPlayerMessageToNpc(sessionId, request.DialogId!, request.Text!); var chatBot = _dialogueChatBots.FirstOrDefault(cb => cb.GetChatBot().Id == request.DialogId @@ -579,7 +579,7 @@ public class DialogueController( /// Session id protected void RemoveExpiredItemsFromMessages(MongoId sessionId) { - foreach (var (dialogId, _) in _dialogueHelper.GetDialogsForProfile(sessionId)) + foreach (var (dialogId, _) in dialogueHelper.GetDialogsForProfile(sessionId)) { RemoveExpiredItemsFromMessage(sessionId, dialogId); } @@ -592,7 +592,7 @@ public class DialogueController( /// Dialog id protected void RemoveExpiredItemsFromMessage(MongoId sessionId, string dialogueId) { - var dialogs = _dialogueHelper.GetDialogsForProfile(sessionId); + var dialogs = dialogueHelper.GetDialogsForProfile(sessionId); if (!dialogs.TryGetValue(dialogueId, out var dialog)) { return; @@ -614,7 +614,7 @@ public class DialogueController( /// True = expired protected bool MessageHasExpired(Message message) { - return _timeUtil.GetTimeStamp() > message.DateTime + (message.MaxStorageTime ?? 0); + return timeUtil.GetTimeStamp() > message.DateTime + (message.MaxStorageTime ?? 0); } /// @@ -629,7 +629,7 @@ public class DialogueController( ) { // To avoid needing to jump between profiles, auto-accept all friend requests - var friendProfile = _profileHelper.GetFullProfile(request.To.Value); + var friendProfile = profileHelper.GetFullProfile(request.To.Value); if (friendProfile?.CharacterData?.PmcData is null) { return new FriendRequestSendResponse @@ -641,7 +641,7 @@ public class DialogueController( } // Only add the profile to the friends list if it doesn't already exist - var profile = _saveServer.GetProfile(sessionID); + var profile = saveServer.GetProfile(sessionID); if (!profile.FriendProfileIds.Contains(request.To)) { profile.FriendProfileIds.Add(request.To); @@ -654,11 +654,11 @@ public class DialogueController( var notification = new WsFriendsListAccept { EventType = NotificationEventType.friendListRequestAccept, - Profile = _profileHelper.GetChatRoomMemberFromPmcProfile( + Profile = profileHelper.GetChatRoomMemberFromPmcProfile( friendProfile.CharacterData.PmcData ), }; - _notificationSendHelper.SendMessage(sessionID, notification); + notificationSendHelper.SendMessage(sessionID, notification); }, null, TimeSpan.FromMicroseconds(1000), @@ -680,7 +680,7 @@ public class DialogueController( /// Sent delete friend request public virtual void DeleteFriend(MongoId sessionID, DeleteFriendRequest request) { - var profile = _saveServer.GetProfile(sessionID); + var profile = saveServer.GetProfile(sessionID); var friendIndex = profile.FriendProfileIds.IndexOf(request.FriendId); if (friendIndex != -1) { @@ -695,10 +695,10 @@ public class DialogueController( /// Client request to clear messages public void ClearMessages(MongoId sessionId, ClearMailMessageRequest request) { - var profile = _saveServer.GetProfile(sessionId); + var profile = saveServer.GetProfile(sessionId); if (!profile.DialogueRecords.TryGetValue(request.DialogId, out var dialogToClear)) { - _logger.Warning( + logger.Warning( $"unable to clear messages from dialog: {request.DialogId} as it cannot be found in profile: {sessionId}" ); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs b/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs index 8c147df2..dd9ca540 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs @@ -20,28 +20,28 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class GameController( - ISptLogger _logger, - IReadOnlyList _loadedMods, - ConfigServer _configServer, - DatabaseService _databaseService, - TimeUtil _timeUtil, - HttpServerHelper _httpServerHelper, - HideoutHelper _hideoutHelper, - ProfileHelper _profileHelper, - ProfileFixerService _profileFixerService, - ServerLocalisationService _serverLocalisationService, - PostDbLoadService _postDbLoadService, - SeasonalEventService _seasonalEventService, - GiftService _giftService, - RaidTimeAdjustmentService _raidTimeAdjustmentService, - ProfileActivityService _profileActivityService + ISptLogger logger, + IReadOnlyList loadedMods, + ConfigServer configServer, + DatabaseService databaseService, + TimeUtil timeUtil, + HttpServerHelper httpServerHelper, + HideoutHelper hideoutHelper, + ProfileHelper profileHelper, + ProfileFixerService profileFixerService, + ServerLocalisationService serverLocalisationService, + PostDbLoadService postDbLoadService, + SeasonalEventService seasonalEventService, + GiftService giftService, + RaidTimeAdjustmentService raidTimeAdjustmentService, + ProfileActivityService profileActivityService ) { - protected readonly BotConfig _botConfig = _configServer.GetConfig(); - protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly BotConfig _botConfig = configServer.GetConfig(); + protected readonly CoreConfig _coreConfig = configServer.GetConfig(); protected readonly double _deviation = 0.0001; - protected readonly HideoutConfig _hideoutConfig = _configServer.GetConfig(); - protected readonly HttpConfig _httpConfig = _configServer.GetConfig(); + protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); + protected readonly HttpConfig _httpConfig = configServer.GetConfig(); /// /// Handle client/game/start @@ -49,13 +49,13 @@ public class GameController( /// /// Session/Player id /// - public void GameStart(string url, string? sessionId, long startTimeStampMs) + public void GameStart(string url, MongoId sessionId, long startTimeStampMs) { - _profileActivityService.AddActiveProfile(sessionId, startTimeStampMs); + profileActivityService.AddActiveProfile(sessionId, startTimeStampMs); - if (sessionId is null) + if (sessionId.IsEmpty()) { - _logger.Error($"{nameof(sessionId)} is null on GameController.GameStart"); + logger.Error($"{nameof(sessionId)} is empty on GameController.GameStart"); return; } @@ -63,10 +63,10 @@ public class GameController( // offraidData). Since we don't want to clutter the Quests list, we need to remove all completed (failed or // successful) repeatable quests. We also have to remove the Counters from the repeatableQuests - var fullProfile = _profileHelper.GetFullProfile(sessionId); + var fullProfile = profileHelper.GetFullProfile(sessionId); if (fullProfile is null) { - _logger.Error($"{nameof(fullProfile)} is null on GameController.GameStart"); + logger.Error($"{nameof(fullProfile)} is null on GameController.GameStart"); return; } @@ -94,12 +94,12 @@ public class GameController( if (fullProfile.DialogueRecords is not null) { - _profileFixerService.CheckForAndFixDialogueAttachments(fullProfile); + profileFixerService.CheckForAndFixDialogueAttachments(fullProfile); } - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Started game with session {sessionId} {fullProfile.ProfileInfo?.Username}" ); } @@ -108,7 +108,7 @@ public class GameController( if (_coreConfig.Fixes.FixProfileBreakingInventoryItemIssues) { - _profileFixerService.FixProfileBreakingInventoryItemIssues(pmcProfile); + profileFixerService.FixProfileBreakingInventoryItemIssues(pmcProfile); } if (pmcProfile.Health is not null) @@ -120,30 +120,30 @@ public class GameController( { SendPraporGiftsToNewProfiles(pmcProfile); SendMechanicGiftsToNewProfile(pmcProfile); - _profileFixerService.CheckForOrphanedModdedItems(sessionId, fullProfile); + profileFixerService.CheckForOrphanedModdedItems(sessionId, fullProfile); } - _profileFixerService.CheckForAndRemoveInvalidTraders(fullProfile); - _profileFixerService.CheckForAndFixPmcProfileIssues(pmcProfile); + profileFixerService.CheckForAndRemoveInvalidTraders(fullProfile); + profileFixerService.CheckForAndFixPmcProfileIssues(pmcProfile); if (pmcProfile.Hideout is not null) { - _profileFixerService.AddMissingHideoutBonusesToProfile( + profileFixerService.AddMissingHideoutBonusesToProfile( pmcProfile, - _databaseService.GetHideout().Areas + databaseService.GetHideout().Areas ); - _hideoutHelper.SetHideoutImprovementsToCompleted(pmcProfile); + hideoutHelper.SetHideoutImprovementsToCompleted(pmcProfile); pmcProfile.UnlockHideoutWallInProfile(); // Handle if player has been inactive for a long time, catch up on hideout update before the user goes to his hideout if ( - !_profileActivityService.ActiveWithinLastMinutes( + !profileActivityService.ActiveWithinLastMinutes( sessionId, _hideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes ) ) { - _hideoutHelper.UpdatePlayerHideout(sessionId); + hideoutHelper.UpdatePlayerHideout(sessionId); } } @@ -161,10 +161,10 @@ public class GameController( WarnOnActiveBotReloadSkill(pmcProfile); } - _seasonalEventService.GivePlayerSeasonalGifts(sessionId); + seasonalEventService.GivePlayerSeasonalGifts(sessionId); // Set activity timestamp at the end of the method, so that code that checks for an older timestamp (Updating hideout) can still run - _profileActivityService.SetActivityTimestamp(sessionId); + profileActivityService.SetActivityTimestamp(sessionId); } /// @@ -172,9 +172,9 @@ public class GameController( /// /// Session/Player id /// GameConfigResponse - public GameConfigResponse GetGameConfig(string sessionId) + public GameConfigResponse GetGameConfig(MongoId sessionId) { - var profile = _profileHelper.GetPmcProfile(sessionId); + var profile = profileHelper.GetPmcProfile(sessionId); var gameTime = profile ?.Stats?.Eft?.OverallCounters?.Items?.FirstOrDefault(c => @@ -184,7 +184,7 @@ public class GameController( var config = new GameConfigResponse { - Languages = _databaseService.GetLocales().Languages, + Languages = databaseService.GetLocales().Languages, IsNdaFree = false, IsReportAvailable = false, IsTwitchEventMember = false, @@ -194,14 +194,14 @@ public class GameController( ActiveProfileId = sessionId, Backend = new Backend { - Lobby = _httpServerHelper.GetBackendUrl(), - Trading = _httpServerHelper.GetBackendUrl(), - Messaging = _httpServerHelper.GetBackendUrl(), - Main = _httpServerHelper.GetBackendUrl(), - RagFair = _httpServerHelper.GetBackendUrl(), + Lobby = httpServerHelper.GetBackendUrl(), + Trading = httpServerHelper.GetBackendUrl(), + Messaging = httpServerHelper.GetBackendUrl(), + Main = httpServerHelper.GetBackendUrl(), + RagFair = httpServerHelper.GetBackendUrl(), }, UseProtobuf = false, - UtcTime = _timeUtil.GetTimeStamp(), + UtcTime = timeUtil.GetTimeStamp(), TotalInGame = gameTime, SessionMode = "pve", PurchasedGames = new PurchasedGames { IsEftPurchased = true, IsArenaPurchased = false }, @@ -217,12 +217,12 @@ public class GameController( /// Session/Player id /// /// - public GameModeResponse GetGameMode(string sessionId, GameModeRequestData requestData) + public GameModeResponse GetGameMode(MongoId sessionId, GameModeRequestData requestData) { return new GameModeResponse { GameMode = "pve", - BackendUrl = _httpServerHelper.GetBackendUrl(), + BackendUrl = httpServerHelper.GetBackendUrl(), }; } @@ -231,7 +231,7 @@ public class GameController( /// /// Session/Player id /// - public List GetServer(string sessionId) + public List GetServer(MongoId sessionId) { return [new ServerDetails { Ip = _httpConfig.BackendIp, Port = _httpConfig.BackendPort }]; } @@ -241,7 +241,7 @@ public class GameController( /// /// Session/Player id /// - public CurrentGroupResponse GetCurrentGroup(string sessionId) + public CurrentGroupResponse GetCurrentGroup(MongoId sessionId) { return new CurrentGroupResponse { Squad = [] }; } @@ -251,7 +251,7 @@ public class GameController( /// /// Session/Player id /// - public CheckVersionResponse GetValidGameVersion(string sessionId) + public CheckVersionResponse GetValidGameVersion(MongoId sessionId) { return new CheckVersionResponse { @@ -265,10 +265,10 @@ public class GameController( /// /// Session/Player id /// - public GameKeepAliveResponse GetKeepAlive(string sessionId) + public GameKeepAliveResponse GetKeepAlive(MongoId sessionId) { - _profileActivityService.SetActivityTimestamp(sessionId); - return new GameKeepAliveResponse { Message = "OK", UtcTime = _timeUtil.GetTimeStamp() }; + profileActivityService.SetActivityTimestamp(sessionId); + return new GameKeepAliveResponse { Message = "OK", UtcTime = timeUtil.GetTimeStamp() }; } /// @@ -277,16 +277,16 @@ public class GameController( /// Session/Player id /// /// - public RaidChanges GetRaidTime(string sessionId, GetRaidTimeRequest request) + public RaidChanges GetRaidTime(MongoId sessionId, GetRaidTimeRequest request) { - return _raidTimeAdjustmentService.GetRaidAdjustments(sessionId, request); + return raidTimeAdjustmentService.GetRaidAdjustments(sessionId, request); } /// /// /// Session/Player id /// - public SurveyResponseData GetSurvey(string sessionId) + public SurveyResponseData GetSurvey(MongoId sessionId) { return _coreConfig.Survey; } @@ -300,8 +300,8 @@ public class GameController( var botReloadSkill = pmcProfile.GetSkillFromProfile(SkillTypes.BotReload); if (botReloadSkill?.Progress > 0) { - _logger.Warning( - _serverLocalisationService.GetText("server_start_player_active_botreload_skill") + logger.Warning( + serverLocalisationService.GetText("server_start_player_active_botreload_skill") ); } } @@ -313,7 +313,7 @@ public class GameController( protected void UpdateProfileHealthValues(PmcData pmcProfile) { var healthLastUpdated = pmcProfile.Health?.UpdateTime; - var currentTimeStamp = _timeUtil.GetTimeStamp(); + var currentTimeStamp = timeUtil.GetTimeStamp(); var diffSeconds = currentTimeStamp - healthLastUpdated; // Update just occurred @@ -440,19 +440,19 @@ public class GameController( protected void SendPraporGiftsToNewProfiles(PmcData pmcProfile) { var timeStampProfileCreated = pmcProfile.Info?.RegistrationDate; - var oneDaySeconds = _timeUtil.GetHoursAsSeconds(24); - var currentTimeStamp = _timeUtil.GetTimeStamp(); + var oneDaySeconds = timeUtil.GetHoursAsSeconds(24); + var currentTimeStamp = timeUtil.GetTimeStamp(); // One day post-profile creation if (currentTimeStamp > timeStampProfileCreated + oneDaySeconds) { - _giftService.SendPraporStartingGift(pmcProfile.SessionId!, 1); + giftService.SendPraporStartingGift(pmcProfile.SessionId!, 1); } // Two day post-profile creation if (currentTimeStamp > timeStampProfileCreated + oneDaySeconds * 2) { - _giftService.SendPraporStartingGift(pmcProfile.SessionId!, 2); + giftService.SendPraporStartingGift(pmcProfile.SessionId!, 2); } } @@ -462,7 +462,7 @@ public class GameController( /// protected void SendMechanicGiftsToNewProfile(PmcData pmcProfile) { - _giftService.SendGiftWithSilentReceivedCheck("MechanicGiftDay1", pmcProfile.SessionId, 1); + giftService.SendGiftWithSilentReceivedCheck("MechanicGiftDay1", pmcProfile.SessionId, 1); } /// @@ -473,7 +473,7 @@ public class GameController( { fullProfile.SptData!.Mods ??= []; - foreach (var mod in _loadedMods) + foreach (var mod in loadedMods) { if ( fullProfile.SptData.Mods.Any(m => @@ -494,7 +494,7 @@ public class GameController( Version = mod.ModMetadata.Version, Name = mod.ModMetadata.Name, Url = mod.ModMetadata.Url, - DateAdded = _timeUtil.GetTimeStamp(), + DateAdded = timeUtil.GetTimeStamp(), } ); } @@ -509,7 +509,7 @@ public class GameController( var playerName = pmcProfile.Info?.Nickname; if (playerName is not null) { - var bots = _databaseService.GetBots().Types; + var bots = databaseService.GetBots().Types; // Official names can only be 15 chars in length if (playerName.Length > _botConfig.BotNameLengthLimit) @@ -553,19 +553,19 @@ public class GameController( /// protected void LogProfileDetails(SptProfile fullProfile) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug($"Profile made with: {fullProfile.SptData?.Version}"); - _logger.Debug( + logger.Debug($"Profile made with: {fullProfile.SptData?.Version}"); + logger.Debug( $"Server version: {ProgramStatics.SPT_VERSION() ?? _coreConfig.SptVersion} {ProgramStatics.COMMIT()}" ); - _logger.Debug($"Debug enabled: {ProgramStatics.DEBUG()}"); - _logger.Debug($"Mods enabled: {ProgramStatics.MODS()}"); + logger.Debug($"Debug enabled: {ProgramStatics.DEBUG()}"); + logger.Debug($"Mods enabled: {ProgramStatics.MODS()}"); } } public void Load() { - _postDbLoadService.PerformPostDbLoadActions(); + postDbLoadService.PerformPostDbLoadActions(); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs b/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs index fdd576f9..133c770c 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs @@ -1,6 +1,7 @@ using SPTarkov.Common.Extensions; using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Health; @@ -17,14 +18,14 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class HealthController( - ISptLogger _logger, - EventOutputHolder _eventOutputHolder, - ItemHelper _itemHelper, - PaymentService _paymentService, - InventoryHelper _inventoryHelper, - ServerLocalisationService _serverLocalisationService, - HttpResponseUtil _httpResponseUtil, - ICloner _cloner + ISptLogger logger, + EventOutputHolder eventOutputHolder, + ItemHelper itemHelper, + PaymentService paymentService, + InventoryHelper inventoryHelper, + ServerLocalisationService serverLocalisationService, + HttpResponseUtil httpResponseUtil, + ICloner cloner ) { /// @@ -37,10 +38,10 @@ public class HealthController( public ItemEventRouterResponse OffRaidHeal( PmcData pmcData, OffraidHealRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); // Update medkit used (hpresource) var healingItemToUse = pmcData.Inventory.Items.FirstOrDefault(item => @@ -48,17 +49,17 @@ public class HealthController( ); if (healingItemToUse is null) { - var errorMessage = _serverLocalisationService.GetText( + var errorMessage = serverLocalisationService.GetText( "health-healing_item_not_found", request.Item ); - _logger.Error(errorMessage); + logger.Error(errorMessage); - return _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + return httpResponseUtil.AppendErrorToOutput(output, errorMessage); } // Ensure item has a upd object - _itemHelper.AddUpdObjectToItem(healingItemToUse); + itemHelper.AddUpdObjectToItem(healingItemToUse); if (healingItemToUse.Upd.MedKit is not null) { @@ -67,7 +68,7 @@ public class HealthController( else { // Get max healing from db - var maxHp = _itemHelper + var maxHp = itemHelper .GetItem(healingItemToUse.Template) .Value.Properties.MaxHpResource; healingItemToUse.Upd.MedKit = new UpdMedKit { HpResource = maxHp - request.Count }; // Subtract amout used from max @@ -78,16 +79,16 @@ public class HealthController( // Resource in medkit is spent, delete it if (healingItemToUse.Upd.MedKit.HpResource <= 0) { - _inventoryHelper.RemoveItem(pmcData, request.Item, sessionID, output); + inventoryHelper.RemoveItem(pmcData, request.Item, sessionID, output); } - var healingItemDbDetails = _itemHelper.GetItem(healingItemToUse.Template); + var healingItemDbDetails = itemHelper.GetItem(healingItemToUse.Template); var healItemEffectDetails = healingItemDbDetails.Value.Properties.EffectsDamage; var bodyPartToHeal = pmcData.Health.BodyParts.GetValueOrDefault(request.Part); if (bodyPartToHeal is null) { - _logger.Warning( + logger.Warning( $"Player: {sessionID} Tried to heal a non-existent body part: {request.Part}" ); @@ -152,32 +153,32 @@ public class HealthController( public ItemEventRouterResponse OffRaidEat( PmcData pmcData, OffraidEatRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); var resourceLeft = 0d; var itemToConsume = pmcData.Inventory.Items.FirstOrDefault(item => item.Id == request.Item); if (itemToConsume is null) // Item not found, very bad { - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText( + serverLocalisationService.GetText( "health-unable_to_find_item_to_consume", request.Item ) ); } - var consumedItemMaxResource = _itemHelper + var consumedItemMaxResource = itemHelper .GetItem(itemToConsume.Template) .Value.Properties.MaxResource; if (consumedItemMaxResource > 1) { // Ensure item has a upd object - _itemHelper.AddUpdObjectToItem(itemToConsume); + itemHelper.AddUpdObjectToItem(itemToConsume); if (itemToConsume.Upd.FoodDrink is null) { @@ -197,11 +198,11 @@ public class HealthController( // Remove item from inventory if resource has dropped below threshold if (consumedItemMaxResource == 1 || resourceLeft < 1) { - _inventoryHelper.RemoveItem(pmcData, request.Item, sessionID, output); + inventoryHelper.RemoveItem(pmcData, request.Item, sessionID, output); } // Check what effect eating item has and handle - var foodItemDbDetails = _itemHelper.GetItem(itemToConsume.Template).Value; + var foodItemDbDetails = itemHelper.GetItem(itemToConsume.Template).Value; var foodItemEffectDetails = foodItemDbDetails.Properties.EffectsHealth; var foodIsSingleUse = foodItemDbDetails.Properties.MaxResource == 1; @@ -222,7 +223,7 @@ public class HealthController( break; default: - _logger.Warning( + logger.Warning( $"Unhandled effect after consuming: {itemToConsume.Template}, {key}" ); break; @@ -282,10 +283,10 @@ public class HealthController( public ItemEventRouterResponse HealthTreatment( PmcData pmcData, HealthTreatmentRequestData healthTreatmentRequest, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); var payMoneyRequest = new ProcessBuyTradeRequestData { Action = healthTreatmentRequest.Action, @@ -297,7 +298,7 @@ public class HealthController( SchemeId = 0, }; - _paymentService.PayMoney(pmcData, payMoneyRequest, sessionID, output); + paymentService.PayMoney(pmcData, payMoneyRequest, sessionID, output); if (output.Warnings.Count > 0) { return output; @@ -334,7 +335,7 @@ public class HealthController( } // Inform client of new post-raid, post-therapist heal values - output.ProfileChanges[sessionID].Health = _cloner.Clone(pmcData.Health); + output.ProfileChanges[sessionID].Health = cloner.Clone(pmcData.Health); return output; } @@ -345,7 +346,7 @@ public class HealthController( /// Player profile /// Request data /// session id - public void ApplyWorkoutChanges(PmcData? pmcData, WorkoutData request, string sessionId) + public void ApplyWorkoutChanges(PmcData? pmcData, WorkoutData request, MongoId sessionId) { pmcData.Skills.Common = request.Skills.Common; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs b/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs index 7a5250a8..952f4e9b 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs @@ -22,25 +22,25 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class HideoutController( - ISptLogger _logger, - TimeUtil _timeUtil, - DatabaseService _databaseService, - InventoryHelper _inventoryHelper, - ItemHelper _itemHelper, - SaveServer _saveServer, - PresetHelper _presetHelper, - PaymentHelper _paymentHelper, - EventOutputHolder _eventOutputHolder, - HttpResponseUtil _httpResponseUtil, - ProfileHelper _profileHelper, - HideoutHelper _hideoutHelper, - ScavCaseRewardGenerator _scavCaseRewardGenerator, - ServerLocalisationService _serverLocalisationService, - ProfileActivityService _profileActivityService, - FenceService _fenceService, - CircleOfCultistService _circleOfCultistService, - ICloner _cloner, - ConfigServer _configServer + ISptLogger logger, + TimeUtil timeUtil, + DatabaseService databaseService, + InventoryHelper inventoryHelper, + ItemHelper itemHelper, + SaveServer saveServer, + PresetHelper presetHelper, + PaymentHelper paymentHelper, + EventOutputHolder eventOutputHolder, + HttpResponseUtil httpResponseUtil, + ProfileHelper profileHelper, + HideoutHelper hideoutHelper, + ScavCaseRewardGenerator scavCaseRewardGenerator, + ServerLocalisationService serverLocalisationService, + ProfileActivityService profileActivityService, + FenceService fenceService, + CircleOfCultistService circleOfCultistService, + ICloner cloner, + ConfigServer configServer ) { public const string NameTaskConditionCountersCraftingId = "673f5d6fdd6ed700c703afdc"; @@ -53,7 +53,7 @@ public class HideoutController( HideoutAreas.BitcoinFarm, ]; - protected readonly HideoutConfig _hideoutConfig = _configServer.GetConfig(); + protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); /// /// Handle HideoutUpgrade event @@ -66,7 +66,7 @@ public class HideoutController( public void StartUpgrade( PmcData pmcData, HideoutUpgradeRequestData request, - string sessionID, + MongoId sessionID, ItemEventRouterResponse output ) { @@ -85,19 +85,19 @@ public class HideoutController( { if (item.inventoryItem is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_item_in_inventory", item.requestedItem.Id ) ); - _httpResponseUtil.AppendErrorToOutput(output); + httpResponseUtil.AppendErrorToOutput(output); return; } if ( - _paymentHelper.IsMoneyTpl(item.inventoryItem.Template) + paymentHelper.IsMoneyTpl(item.inventoryItem.Template) && item.inventoryItem.Upd is not null && item.inventoryItem.Upd.StackObjectsCount is not null && item.inventoryItem.Upd.StackObjectsCount > item.requestedItem.Count @@ -107,7 +107,7 @@ public class HideoutController( } else { - _inventoryHelper.RemoveItem(pmcData, item.inventoryItem.Id, sessionID, output); + inventoryHelper.RemoveItem(pmcData, item.inventoryItem.Id, sessionID, output); } } @@ -117,26 +117,26 @@ public class HideoutController( ); if (profileHideoutArea is null) { - _logger.Error( - _serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) + logger.Error( + serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) ); - _httpResponseUtil.AppendErrorToOutput(output); + httpResponseUtil.AppendErrorToOutput(output); return; } - var hideoutDataDb = _databaseService + var hideoutDataDb = databaseService .GetTables() .Hideout.Areas.FirstOrDefault(area => area.Type == request.AreaType); if (hideoutDataDb is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_area_in_database", request.AreaType ) ); - _httpResponseUtil.AppendErrorToOutput(output); + httpResponseUtil.AppendErrorToOutput(output); return; } @@ -146,12 +146,12 @@ public class HideoutController( .ConstructionTime; if (ctime > 0) { - if (_profileHelper.IsDeveloperAccount(sessionID)) + if (profileHelper.IsDeveloperAccount(sessionID)) { ctime = 40; } - var timestamp = _timeUtil.GetTimeStamp(); + var timestamp = timeUtil.GetTimeStamp(); profileHideoutArea.CompleteTime = (int)Math.Round(timestamp + ctime.Value); profileHideoutArea.Constructing = true; @@ -169,22 +169,22 @@ public class HideoutController( public void UpgradeComplete( PmcData pmcData, HideoutUpgradeCompleteRequestData request, - string sessionID, + MongoId sessionID, ItemEventRouterResponse output ) { - var hideout = _databaseService.GetHideout(); - var globals = _databaseService.GetGlobals(); + var hideout = databaseService.GetHideout(); + var globals = databaseService.GetGlobals(); var profileHideoutArea = pmcData.Hideout.Areas.FirstOrDefault(area => area.Type == request.AreaType ); if (profileHideoutArea is null) { - _logger.Error( - _serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) + logger.Error( + serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) ); - _httpResponseUtil.AppendErrorToOutput(output); + httpResponseUtil.AppendErrorToOutput(output); return; } @@ -199,13 +199,13 @@ public class HideoutController( ); if (hideoutData is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_area_in_database", request.AreaType ) ); - _httpResponseUtil.AppendErrorToOutput(output); + httpResponseUtil.AppendErrorToOutput(output); return; } @@ -217,7 +217,7 @@ public class HideoutController( { foreach (var bonus in bonuses) { - _hideoutHelper.ApplyPlayerUpgradesBonuses(pmcData, bonus); + hideoutHelper.ApplyPlayerUpgradesBonuses(pmcData, bonus); } } @@ -246,11 +246,11 @@ public class HideoutController( // Cleanup temporary buffs/debuffs from wall if complete if (profileHideoutArea.Type == HideoutAreas.EmergencyWall && profileHideoutArea.Level == 6) { - _hideoutHelper.RemoveHideoutWallBuffsAndDebuffs(hideoutData, pmcData); + hideoutHelper.RemoveHideoutWallBuffsAndDebuffs(hideoutData, pmcData); } // Add Skill Points Per Area Upgrade - _profileHelper.AddSkillPointsToPlayer( + profileHelper.AddSkillPointsToPlayer( pmcData, SkillTypes.HideoutManagement, globals.Configuration.SkillsSettings.HideoutManagement.SkillPointsPerAreaUpgrade @@ -292,7 +292,7 @@ public class HideoutController( /// Stage player is upgrading to protected void AddContainerImprovementToProfile( ItemEventRouterResponse output, - string sessionId, + MongoId sessionId, PmcData pmcData, BotHideoutArea profileParentHideoutArea, HideoutArea dbHideoutArea, @@ -311,7 +311,7 @@ public class HideoutController( ) ) { - _logger.Error($"Unable to add key: {dbHideoutArea.Type} to HideoutAreaStashes"); + logger.Error($"Unable to add key: {dbHideoutArea.Type} to HideoutAreaStashes"); } } @@ -340,7 +340,7 @@ public class HideoutController( ); // Some hideout areas (Gun stand) have child areas linked to it - var childDbArea = _databaseService + var childDbArea = databaseService .GetHideout() .Areas.FirstOrDefault(area => area.ParentArea == dbHideoutArea.Id); if (childDbArea is null) @@ -371,7 +371,7 @@ public class HideoutController( ) ) { - _logger.Error( + logger.Error( $"Unable to find stage: {profileParentHideoutArea.Level} of area: {dbHideoutArea.Id}" ); @@ -398,7 +398,7 @@ public class HideoutController( /// Hideout area from db being upgraded /// Stage area upgraded to protected void AddUpdateInventoryItemToProfile( - string sessionId, + MongoId sessionId, PmcData pmcData, HideoutArea dbHideoutArea, Stage hideoutStage @@ -433,7 +433,7 @@ public class HideoutController( /// /// Client response protected void AddContainerUpgradeToClientOutput( - string sessionId, + MongoId sessionId, string changedHideoutStashesKey, HideoutArea hideoutDbData, Stage hideoutStage, @@ -460,10 +460,10 @@ public class HideoutController( public ItemEventRouterResponse PutItemsInAreaSlots( PmcData pmcData, HideoutPutItemInRequestData addItemToHideoutRequest, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); var itemsToAdd = addItemToHideoutRequest.Items.Select(kvp => { @@ -483,26 +483,26 @@ public class HideoutController( ); if (hideoutArea is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_area_in_database", addItemToHideoutRequest.AreaType ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } foreach (var item in itemsToAdd) { if (item.inventoryItem is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_item_in_inventory", new { itemId = item.requestedItem.Id, area = hideoutArea.Type } ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } // Add item to area.slots @@ -512,7 +512,7 @@ public class HideoutController( ); if (hideoutSlotIndex == -1) { - _logger.Error( + logger.Error( $"Unable to put item: {item.requestedItem.Id} into slot as slot cannot be found for area: {addItemToHideoutRequest.AreaType}, skipping" ); continue; @@ -528,11 +528,11 @@ public class HideoutController( }, ]; - _inventoryHelper.RemoveItem(pmcData, item.inventoryItem.Id, sessionID, output); + inventoryHelper.RemoveItem(pmcData, item.inventoryItem.Id, sessionID, output); } // Trigger a forced update - _hideoutHelper.UpdatePlayerHideout(sessionID); + hideoutHelper.UpdatePlayerHideout(sessionID); return output; } @@ -548,31 +548,31 @@ public class HideoutController( public ItemEventRouterResponse TakeItemsFromAreaSlots( PmcData pmcData, HideoutTakeItemOutRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); var hideoutArea = pmcData.Hideout.Areas.FirstOrDefault(area => area.Type == request.AreaType ); if (hideoutArea is null) { - _logger.Error( - _serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) + logger.Error( + serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } if (hideoutArea.Slots is null || hideoutArea.Slots.Count == 0) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_item_to_remove_from_area", hideoutArea.Type ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } // Handle areas that have resources that can be placed in/taken out of slots from the area @@ -581,12 +581,12 @@ public class HideoutController( var response = RemoveResourceFromArea(sessionID, pmcData, request, output, hideoutArea); // Force a refresh of productions/hideout areas with resources - _hideoutHelper.UpdatePlayerHideout(sessionID); + hideoutHelper.UpdatePlayerHideout(sessionID); return response; } throw new Exception( - _serverLocalisationService.GetText( + serverLocalisationService.GetText( "hideout-unhandled_remove_item_from_area_request", hideoutArea.Type ) @@ -603,7 +603,7 @@ public class HideoutController( /// Area fuel is being removed from /// ItemEventRouterResponse protected ItemEventRouterResponse RemoveResourceFromArea( - string sessionID, + MongoId sessionID, PmcData pmcData, HideoutTakeItemOutRequestData removeResourceRequest, ItemEventRouterResponse output, @@ -613,7 +613,7 @@ public class HideoutController( var slotIndexToRemove = removeResourceRequest?.Slots?.FirstOrDefault(); if (slotIndexToRemove is null) { - _logger.Error( + logger.Error( $"Unable to remove resource from area: {removeResourceRequest.AreaType} slot as no slots found in request, RESTART CLIENT IMMEDIATELY" ); @@ -626,7 +626,7 @@ public class HideoutController( ?.Items?.FirstOrDefault(); if (itemToReturn is null) { - _logger.Error( + logger.Error( $"Unable to remove resource from area: {removeResourceRequest.AreaType} slot as no item found, RESTART CLIENT IMMEDIATELY" ); @@ -642,7 +642,7 @@ public class HideoutController( UseSortingTable = false, }; - _inventoryHelper.AddItemToStash(sessionID, request, pmcData, output); + inventoryHelper.AddItemToStash(sessionID, request, pmcData, output); if (output.Warnings?.Count > 0) // Adding to stash failed, drop out - don't remove item from hideout area slot { @@ -669,23 +669,23 @@ public class HideoutController( public ItemEventRouterResponse ToggleArea( PmcData pmcData, HideoutToggleAreaRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); // Force a production update (occur before area is toggled as it could be generator and doing it after generator enabled would cause incorrect calculaton of production progress) - _hideoutHelper.UpdatePlayerHideout(sessionID); + hideoutHelper.UpdatePlayerHideout(sessionID); var hideoutArea = pmcData.Hideout.Areas.FirstOrDefault(area => area.Type == request.AreaType ); if (hideoutArea is null) { - _logger.Error( - _serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) + logger.Error( + serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } hideoutArea.Active = request.Enabled; @@ -703,24 +703,24 @@ public class HideoutController( public ItemEventRouterResponse SingleProductionStart( PmcData pmcData, HideoutSingleProductionStartRequestData request, - string sessionID + MongoId sessionID ) { // Start production - _hideoutHelper.RegisterProduction(pmcData, request, sessionID); + hideoutHelper.RegisterProduction(pmcData, request, sessionID); // Find the recipe of the production - var recipe = _databaseService + var recipe = databaseService .GetHideout() .Production.Recipes.FirstOrDefault(production => production.Id == request.RecipeId); // Find the actual amount of items we need to remove because body can send weird data - var recipeRequirementsClone = _cloner.Clone( + var recipeRequirementsClone = cloner.Clone( recipe.Requirements.Where(r => r.Type == "Item" || r.Type == "Tool") ); List itemsToDelete = []; - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); itemsToDelete.AddRange(request.Tools); itemsToDelete.AddRange(request.Items); @@ -738,7 +738,7 @@ public class HideoutController( continue; } - _inventoryHelper.RemoveItemByCount( + inventoryHelper.RemoveItemByCount( pmcData, itemToDelete.Id, requiredCount, @@ -767,10 +767,10 @@ public class HideoutController( public ItemEventRouterResponse ScavCaseProductionStart( PmcData pmcData, HideoutScavCaseStartRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); foreach (var requestedItem in request.Items) { @@ -779,13 +779,13 @@ public class HideoutController( ); if (inventoryItem is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_scavcase_requested_item_in_profile_inventory", requestedItem.Id ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } if ( @@ -797,23 +797,23 @@ public class HideoutController( } else { - _inventoryHelper.RemoveItem(pmcData, requestedItem.Id, sessionID, output); + inventoryHelper.RemoveItem(pmcData, requestedItem.Id, sessionID, output); } } - var recipe = _databaseService + var recipe = databaseService .GetHideout() .Production?.ScavRecipes?.FirstOrDefault(r => r.Id == request.RecipeId); if (recipe is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_scav_case_recipie_in_database", request.RecipeId ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } // @Important: Here we need to be very exact: @@ -821,20 +821,20 @@ public class HideoutController( // - scav case recipe: Production time value is stored in attribute "ProductionTime" with capital "P" var adjustedCraftTime = recipe.ProductionTime - - _hideoutHelper.GetSkillProductionTimeReduction( + - hideoutHelper.GetSkillProductionTimeReduction( pmcData, recipe.ProductionTime ?? 0, SkillTypes.Crafting, - _databaseService + databaseService .GetGlobals() .Configuration.SkillsSettings.Crafting.CraftTimeReductionPerLevel ?? 0 ); var modifiedScavCaseTime = GetScavCaseTime(pmcData, adjustedCraftTime); - pmcData.Hideout.Production[request.RecipeId] = _hideoutHelper.InitProduction( + pmcData.Hideout.Production[request.RecipeId] = hideoutHelper.InitProduction( request.RecipeId, - (int)(_profileHelper.IsDeveloperAccount(sessionID) ? 40 : modifiedScavCaseTime), + (int)(profileHelper.IsDeveloperAccount(sessionID) ? 40 : modifiedScavCaseTime), false ); pmcData.Hideout.Production[request.RecipeId].SptIsScavCase = true; @@ -850,7 +850,7 @@ public class HideoutController( /// Adjusted scav case time in seconds protected double? GetScavCaseTime(PmcData pmcData, double? productionTime) { - var fenceLevel = _fenceService.GetFenceInfo(pmcData); + var fenceLevel = fenceService.GetFenceInfo(pmcData); if (fenceLevel is null) { return productionTime; @@ -865,7 +865,7 @@ public class HideoutController( /// Players PMC profile /// reward items to add to profile /// recipe id to save into Production dict - public void AddScavCaseRewardsToProfile(PmcData pmcData, List rewards, string recipeId) + public void AddScavCaseRewardsToProfile(PmcData pmcData, List rewards, MongoId recipeId) { pmcData.Hideout.Production[$"ScavCase{recipeId}"] = new Production { @@ -884,12 +884,12 @@ public class HideoutController( public ItemEventRouterResponse ContinuousProductionStart( PmcData pmcData, HideoutContinuousProductionStartRequestData request, - string sessionID + MongoId sessionID ) { - _hideoutHelper.RegisterProduction(pmcData, request, sessionID); + hideoutHelper.RegisterProduction(pmcData, request, sessionID); - return _eventOutputHolder.GetOutput(sessionID); + return eventOutputHolder.GetOutput(sessionID); } /// @@ -903,17 +903,17 @@ public class HideoutController( public ItemEventRouterResponse TakeProduction( PmcData pmcData, HideoutTakeProductionRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); - var hideoutDb = _databaseService.GetHideout(); + var output = eventOutputHolder.GetOutput(sessionID); + var hideoutDb = databaseService.GetHideout(); if (request.RecipeId == HideoutHelper.BitcoinProductionId) { // Ensure server and client are in-sync when player presses 'get items' on farm - _hideoutHelper.UpdatePlayerHideout(sessionID); - _hideoutHelper.GetBTC(pmcData, request, sessionID, output); + hideoutHelper.UpdatePlayerHideout(sessionID); + hideoutHelper.GetBTC(pmcData, request, sessionID, output); return output; } @@ -936,14 +936,14 @@ public class HideoutController( return output; } - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_production_in_profile_by_recipie_id", request.RecipeId ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } /// @@ -955,7 +955,7 @@ public class HideoutController( /// Remove production from area request /// Client response protected void HandleRecipe( - string sessionID, + MongoId sessionID, HideoutProduction recipe, PmcData pmcData, HideoutTakeProductionRequestData request, @@ -986,16 +986,16 @@ public class HideoutController( // If we're unable to find the production, send an error to the client if (prodId is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_production_in_profile_by_recipie_id", request.RecipeId ) ); - _httpResponseUtil.AppendErrorToOutput( + httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText( + serverLocalisationService.GetText( "hideout-unable_to_find_production_in_profile_by_recipie_id", request.RecipeId ) @@ -1014,7 +1014,7 @@ public class HideoutController( List> itemAndChildrenToSendToPlayer = []; // Reward is weapon/armor preset, handle differently compared to 'normal' items - var rewardIsPreset = _presetHelper.HasPreset(recipe.EndProduct); + var rewardIsPreset = presetHelper.HasPreset(recipe.EndProduct); if (rewardIsPreset) { itemAndChildrenToSendToPlayer = HandlePresetReward(recipe); @@ -1027,7 +1027,7 @@ public class HideoutController( { foreach (var reward in itemAndChildrenToSendToPlayer) { - _itemHelper.AddUpdObjectToItem(reward.FirstOrDefault()); + itemHelper.AddUpdObjectToItem(reward.FirstOrDefault()); reward.FirstOrDefault().Upd.RecodableComponent = new UpdRecodableComponent { @@ -1073,11 +1073,11 @@ public class HideoutController( totalResultItems.AddRange(itemAndChildrenToSendToPlayer); totalResultItems.AddRange(toolsToSendToPlayer); - if (!_inventoryHelper.CanPlaceItemsInInventory(sessionID, totalResultItems)) + if (!inventoryHelper.CanPlaceItemsInInventory(sessionID, totalResultItems)) { - _httpResponseUtil.AppendErrorToOutput( + httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText("inventory-no_stash_space"), + serverLocalisationService.GetText("inventory-no_stash_space"), BackendErrorCodes.NotEnoughSpace ); return; @@ -1095,7 +1095,7 @@ public class HideoutController( Callback = null, }; - _inventoryHelper.AddItemsToStash(sessionID, addToolsRequest, pmcData, output); + inventoryHelper.AddItemsToStash(sessionID, addToolsRequest, pmcData, output); if (output.Warnings?.Count > 0) { return; @@ -1110,7 +1110,7 @@ public class HideoutController( UseSortingTable = false, Callback = null, }; - _inventoryHelper.AddItemsToStash(sessionID, addItemsRequest, pmcData, output); + inventoryHelper.AddItemsToStash(sessionID, addItemsRequest, pmcData, output); if (output.Warnings?.Count > 0) { return; @@ -1120,8 +1120,8 @@ public class HideoutController( // - delete the production in profile Hideout.Production // Hideout Management skill // ? use a configuration variable for the value? - var globals = _databaseService.GetGlobals(); - _profileHelper.AddSkillPointsToPlayer( + var globals = databaseService.GetGlobals(); + profileHelper.AddSkillPointsToPlayer( pmcData, SkillTypes.HideoutManagement, globals.Configuration.SkillsSettings.HideoutManagement.SkillPointsPerCraft, @@ -1131,12 +1131,12 @@ public class HideoutController( // Add Crafting skill to player profile if (craftingExpAmount > 0) { - _profileHelper.AddSkillPointsToPlayer(pmcData, SkillTypes.Crafting, craftingExpAmount); + profileHelper.AddSkillPointsToPlayer(pmcData, SkillTypes.Crafting, craftingExpAmount); var intellectAmountToGive = 0.5 * Math.Round((double)(craftingExpAmount / 15)); if (intellectAmountToGive > 0) { - _profileHelper.AddSkillPointsToPlayer( + profileHelper.AddSkillPointsToPlayer( pmcData, SkillTypes.Intellect, intellectAmountToGive @@ -1157,7 +1157,7 @@ public class HideoutController( // production.json is set to if (recipe.Continuous.GetValueOrDefault(false)) { - hideoutProduction.ProductionTime = _hideoutHelper.GetAdjustedCraftTimeWithSkills( + hideoutProduction.ProductionTime = hideoutHelper.GetAdjustedCraftTimeWithSkills( pmcData, recipe.Id, true @@ -1183,7 +1183,7 @@ public class HideoutController( bool rewardIsPreset ) { - var rewardIsStackable = _itemHelper.IsItemTplStackable(recipe.EndProduct); + var rewardIsStackable = itemHelper.IsItemTplStackable(recipe.EndProduct); if (rewardIsStackable.GetValueOrDefault(false)) { // Create root item @@ -1195,7 +1195,7 @@ public class HideoutController( }; // Split item into separate items with acceptable stack sizes - var splitReward = _itemHelper.SplitStackIntoSeparateItems(rewardToAdd); + var splitReward = itemHelper.SplitStackIntoSeparateItems(rewardToAdd); itemAndChildrenToSendToPlayer.AddRange(splitReward); return; @@ -1216,7 +1216,7 @@ public class HideoutController( var countOfItemsToReward = recipe.Count; for (var index = 1; index < countOfItemsToReward; index++) { - var firstItemWithChildrenClone = _cloner + var firstItemWithChildrenClone = cloner .Clone(itemAndChildrenToSendToPlayer.FirstOrDefault()) .ReplaceIDs() .ToList(); @@ -1231,10 +1231,10 @@ public class HideoutController( /// protected List> HandlePresetReward(HideoutProduction recipe) { - var defaultPreset = _presetHelper.GetDefaultPreset(recipe.EndProduct); + var defaultPreset = presetHelper.GetDefaultPreset(recipe.EndProduct); // Ensure preset has unique ids and is cloned so we don't alter the preset data stored in memory - var presetAndModsClone = _cloner.Clone(defaultPreset.Items).ReplaceIDs().ToList(); + var presetAndModsClone = cloner.Clone(defaultPreset.Items).ReplaceIDs().ToList(); presetAndModsClone.RemapRootItemId(); @@ -1277,7 +1277,7 @@ public class HideoutController( /// Get rewards from scavcase craft request /// Client response protected void HandleScavCase( - string sessionID, + MongoId sessionID, PmcData pmcData, HideoutTakeProductionRequestData request, ItemEventRouterResponse output @@ -1297,20 +1297,20 @@ public class HideoutController( if (prodId == null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_production_in_profile_by_recipie_id", request.RecipeId ) ); - _httpResponseUtil.AppendErrorToOutput(output); + httpResponseUtil.AppendErrorToOutput(output); return; } // Create rewards for scav case - var scavCaseRewards = _scavCaseRewardGenerator.Generate(request.RecipeId); + var scavCaseRewards = scavCaseRewardGenerator.Generate(request.RecipeId); var addItemsRequest = new AddItemsDirectRequest { @@ -1320,7 +1320,7 @@ public class HideoutController( UseSortingTable = false, }; - _inventoryHelper.AddItemsToStash(sessionID, addItemsRequest, pmcData, output); + inventoryHelper.AddItemsToStash(sessionID, addItemsRequest, pmcData, output); if (output.Warnings?.Count > 0) { return; @@ -1345,7 +1345,7 @@ public class HideoutController( /// QTE result object /// Client response public void HandleQTEEventOutcome( - string sessionId, + MongoId sessionId, PmcData pmcData, HandleQTEEventRequestData request, ItemEventRouterResponse output @@ -1361,7 +1361,7 @@ public class HideoutController( // Skill changes are done in // /client/hideout/workout (applyWorkoutChanges). - var qteDb = _databaseService.GetHideout().Qte; + var qteDb = databaseService.GetHideout().Qte; var relevantQte = qteDb.FirstOrDefault(qte => qte.Id == request.Id); foreach (var outcome in request.Results) { @@ -1447,7 +1447,7 @@ public class HideoutController( /// Players PMC profile /// shooting range score request> public void RecordShootingRangePoints( - string sessionId, + MongoId sessionId, PmcData pmcData, RecordShootingRangePoints request ) @@ -1479,12 +1479,12 @@ public class HideoutController( /// Improve area request /// ItemEventRouterResponse public ItemEventRouterResponse ImproveArea( - string sessionId, + MongoId sessionId, PmcData pmcData, HideoutImproveAreaRequestData request ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); // Create mapping of required item with corresponding item from player inventory var items = request.Items.Select(reqItem => @@ -1498,17 +1498,17 @@ public class HideoutController( { if (item.inventoryItem is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_item_in_inventory", item.requestedItem.Id ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } if ( - _paymentHelper.IsMoneyTpl(item.inventoryItem.Template) + paymentHelper.IsMoneyTpl(item.inventoryItem.Template) && item.inventoryItem.Upd is not null && item.inventoryItem.Upd.StackObjectsCount is not null && item.inventoryItem.Upd.StackObjectsCount > item.requestedItem.Count @@ -1518,7 +1518,7 @@ public class HideoutController( } else { - _inventoryHelper.RemoveItem(pmcData, item.inventoryItem.Id, sessionId, output); + inventoryHelper.RemoveItem(pmcData, item.inventoryItem.Id, sessionId, output); } } @@ -1527,29 +1527,29 @@ public class HideoutController( ); if (profileHideoutArea is null) { - _logger.Error( - _serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) + logger.Error( + serverLocalisationService.GetText("hideout-unable_to_find_area", request.AreaType) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } - var hideoutDbData = _databaseService + var hideoutDbData = databaseService .GetHideout() .Areas.FirstOrDefault(area => area.Type == request.AreaType); if (hideoutDbData is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "hideout-unable_to_find_area_in_database", request.AreaType ) ); - return _httpResponseUtil.AppendErrorToOutput(output); + return httpResponseUtil.AppendErrorToOutput(output); } // Add all improvemets to output object var improvements = hideoutDbData.Stages[profileHideoutArea.Level.ToString()].Improvements; - var timestamp = _timeUtil.GetTimeStamp(); + var timestamp = timeUtil.GetTimeStamp(); if (output.ProfileChanges[sessionId].Improvements is null) { @@ -1581,20 +1581,20 @@ public class HideoutController( /// Cancel production request data /// ItemEventRouterResponse public ItemEventRouterResponse CancelProduction( - string sessionId, + MongoId sessionId, PmcData pmcData, HideoutCancelProductionRequestData request ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); var craftToCancel = pmcData.Hideout.Production[request.RecipeId]; if (craftToCancel is null) { var errorMessage = $"Unable to find craft {request.RecipeId} to cancel"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - return _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + return httpResponseUtil.AppendErrorToOutput(output, errorMessage); } // Null out production data so client gets informed when response send back @@ -1611,7 +1611,7 @@ public class HideoutController( HideoutCircleOfCultistProductionStartRequestData request ) { - return _circleOfCultistService.StartSacrifice(sessionId, pmcData, request); + return circleOfCultistService.StartSacrifice(sessionId, pmcData, request); } /// @@ -1622,12 +1622,12 @@ public class HideoutController( /// Delete production request /// ItemEventRouterResponse public ItemEventRouterResponse HideoutDeleteProductionCommand( - string sessionId, + MongoId sessionId, PmcData pmcData, HideoutDeleteProductionRequestData request ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); pmcData.Hideout.Production[request.RecipeId] = null; output.ProfileChanges[sessionId].Production = null; @@ -1643,19 +1643,19 @@ public class HideoutController( /// Apply hideout customisation request /// ItemEventRouterResponse public ItemEventRouterResponse HideoutCustomizationApply( - string sessionId, + MongoId sessionId, PmcData pmcData, HideoutCustomizationApplyRequestData request ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); - var itemDetails = _databaseService + var itemDetails = databaseService .GetHideout() .Customisation.Globals.FirstOrDefault(cust => cust.Id == request.OfferId); if (itemDetails is null) { - _logger.Error( + logger.Error( $"Unable to find customisation: {request.OfferId} in db, cannot apply to hideout" ); @@ -1688,7 +1688,7 @@ public class HideoutController( case "shootingRangeMark": return "ShootingRangeMark"; default: - _logger.Warning($"Unknown {type}, unable to map"); + logger.Warning($"Unknown {type}, unable to map"); return type; } } @@ -1702,7 +1702,7 @@ public class HideoutController( /// /// Client response protected void AddMissingPresetStandItemsToProfile( - string sessionId, + MongoId sessionId, Stage equipmentPresetStage, PmcData pmcData, HideoutArea equipmentPresetHideoutArea, @@ -1710,7 +1710,7 @@ public class HideoutController( ) { // Each slot is a single Mannequin - var slots = _itemHelper.GetItem(equipmentPresetStage.Container).Value.Properties.Slots; + var slots = itemHelper.GetItem(equipmentPresetStage.Container).Value.Properties.Slots; foreach (var mannequinSlot in slots) { // Check if we've already added this mannequin @@ -1758,17 +1758,17 @@ public class HideoutController( /// Client request /// public ItemEventRouterResponse HideoutCustomizationSetMannequinPose( - string sessionId, + MongoId sessionId, PmcData pmcData, HideoutCustomizationSetMannequinPoseRequest request ) { if (request.Poses is null) { - _logger.Warning( + logger.Warning( "this really shouldnt be possible, but a request has come in with a pose change without poses" ); - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } foreach (var poseKvP in request.Poses) @@ -1778,7 +1778,7 @@ public class HideoutController( pmcData.Hideout.MannequinPoses[poseKvP.Key] = poseKvP.Value; } - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -1787,9 +1787,9 @@ public class HideoutController( /// /// Session/Player id /// - public List GetQteList(string sessionId) + public List GetQteList(MongoId sessionId) { - return _databaseService.GetHideout().Qte; + return databaseService.GetHideout().Qte; } /// @@ -1798,17 +1798,17 @@ public class HideoutController( /// public void Update() { - foreach (var (sessionId, profile) in _saveServer.GetProfiles()) + foreach (var (sessionId, profile) in saveServer.GetProfiles()) { if ( profile.CharacterData.PmcData.Hideout is not null - && _profileActivityService.ActiveWithinLastMinutes( + && profileActivityService.ActiveWithinLastMinutes( sessionId, _hideoutConfig.UpdateProfileHideoutWhenActiveWithinMinutes ) ) { - _hideoutHelper.UpdatePlayerHideout(sessionId); + hideoutHelper.UpdatePlayerHideout(sessionId); } } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs index 8b659658..c44bbd13 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InRaidController.cs @@ -1,5 +1,6 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.InRaid; using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Utils; @@ -9,21 +10,21 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class InRaidController( - ISptLogger _logger, - ProfileHelper _profileHelper, + ISptLogger logger, + ProfileHelper profileHelper, //ApplicationContext _applicationContext, - ConfigServer _configServer + ConfigServer configServer ) { - protected readonly BotConfig _botConfig = _configServer.GetConfig(); - protected readonly InRaidConfig _inRaidConfig = _configServer.GetConfig(); + protected readonly BotConfig _botConfig = configServer.GetConfig(); + protected readonly InRaidConfig _inRaidConfig = configServer.GetConfig(); /// /// Save locationId to active profiles in-raid object AND app context /// /// Session id /// Register player request - public void AddPlayer(string sessionId, RegisterPlayerRequestData info) + public void AddPlayer(MongoId sessionId, RegisterPlayerRequestData info) { // _applicationContext.AddValue(ContextVariableType.REGISTER_PLAYER_REQUEST, info); } @@ -35,9 +36,12 @@ public class InRaidController( /// /// /// Session/Player id - public void SavePostRaidProfileForScav(ScavSaveRequestData offRaidProfileData, string sessionId) + public void SavePostRaidProfileForScav( + ScavSaveRequestData offRaidProfileData, + MongoId sessionId + ) { - var serverScavProfile = _profileHelper.GetScavProfile(sessionId); + var serverScavProfile = profileHelper.GetScavProfile(sessionId); // If equipment match overwrite existing data from update to date raid data for scavenger screen to work correctly. // otherwise Scav inventory will be overwritten and break scav regeneration, breaking profile. @@ -62,7 +66,7 @@ public class InRaidController( /// /// Session/Player id /// % chance scav is hostile to player - public double GetTraitorScavHostileChance(string url, string sessionId) + public double GetTraitorScavHostileChance(string url, MongoId sessionId) { return _inRaidConfig.PlayerScavHostileChancePercent; } @@ -73,7 +77,7 @@ public class InRaidController( /// /// Session/Player id /// string array of boss types - public List GetBossTypes(string url, string sessionId) + public List GetBossTypes(string url, MongoId sessionId) { return _botConfig.Bosses; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs index b653942b..50cec711 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs @@ -23,27 +23,26 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class InsuranceController( - ISptLogger _logger, - RandomUtil _randomUtil, - TimeUtil _timeUtil, - EventOutputHolder _eventOutputHolder, - ItemHelper _itemHelper, - ProfileHelper _profileHelper, - WeightedRandomHelper _weightedRandomHelper, - PaymentService _paymentService, - InsuranceService _insuranceService, - DatabaseService _databaseService, - MailSendService _mailSendService, - RagfairPriceService _ragfairPriceService, - ServerLocalisationService _serverLocalisationService, - SaveServer _saveServer, - TraderStore _traderStore, - ConfigServer _configServer, - ICloner _cloner + ISptLogger logger, + RandomUtil randomUtil, + TimeUtil timeUtil, + EventOutputHolder eventOutputHolder, + ItemHelper itemHelper, + ProfileHelper profileHelper, + WeightedRandomHelper weightedRandomHelper, + PaymentService paymentService, + InsuranceService insuranceService, + DatabaseService databaseService, + MailSendService mailSendService, + RagfairPriceService ragfairPriceService, + ServerLocalisationService serverLocalisationService, + SaveServer saveServer, + TraderStore traderStore, + ConfigServer configServer, + ICloner cloner ) { - protected readonly InsuranceConfig _insuranceConfig = - _configServer.GetConfig(); + protected readonly InsuranceConfig _insuranceConfig = configServer.GetConfig(); /// /// Process insurance items of all profiles prior to being given back to the player through the mail service @@ -51,7 +50,7 @@ public class InsuranceController( public void ProcessReturn() { // Process each installed profile. - foreach (var sessionId in _saveServer.GetProfiles()) + foreach (var sessionId in saveServer.GetProfiles()) { ProcessReturnByProfile(sessionId.Key); } @@ -61,7 +60,7 @@ public class InsuranceController( /// Process insurance items of a single profile prior to being given back to the player through the mail service /// /// Player id - public void ProcessReturnByProfile(string sessionId) + public void ProcessReturnByProfile(MongoId sessionId) { // Filter out items that don't need to be processed yet. var insuranceDetails = FilterInsuredItems(sessionId); @@ -81,17 +80,17 @@ public class InsuranceController( /// Session/Player id /// The time to check ready status against. Current time by default /// All insured items that are ready to be processed - protected List FilterInsuredItems(string sessionId, long? time = null) + protected List FilterInsuredItems(MongoId sessionId, long? time = null) { // Use the current time by default. - var insuranceTime = time ?? _timeUtil.GetTimeStamp(); + var insuranceTime = time ?? timeUtil.GetTimeStamp(); - var profileInsuranceDetails = _saveServer.GetProfile(sessionId).InsuranceList; + var profileInsuranceDetails = saveServer.GetProfile(sessionId).InsuranceList; if (profileInsuranceDetails.Count > 0) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Found {profileInsuranceDetails.Count} insurance packages in profile {sessionId}" ); } @@ -107,11 +106,11 @@ public class InsuranceController( /// /// The insured items to process /// session ID that should receive the processed items - protected void ProcessInsuredItems(List insuranceDetails, string sessionId) + protected void ProcessInsuredItems(List insuranceDetails, MongoId sessionId) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Processing {insuranceDetails.Count} insurance packages, which includes a total of: {CountAllInsuranceItems(insuranceDetails)} items, in profile: {sessionId}" ); } @@ -160,9 +159,9 @@ public class InsuranceController( /// /// The session ID of the profile to remove the package from. /// The array index of the insurance package to remove. - protected void RemoveInsurancePackageFromProfile(string sessionId, Insurance insPackage) + protected void RemoveInsurancePackageFromProfile(MongoId sessionId, Insurance insPackage) { - var profile = _saveServer.GetProfile(sessionId); + var profile = saveServer.GetProfile(sessionId); profile.InsuranceList = profile .InsuranceList.Where(insurance => insurance.TraderId != insPackage.TraderId @@ -172,9 +171,9 @@ public class InsuranceController( ) .ToList(); - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Removed processed insurance package. Remaining packages: {profile.InsuranceList.Count}" ); } @@ -200,7 +199,7 @@ public class InsuranceController( ); // Check to see if any regular items are present. - var hasRegularItems = itemsMap.Values.Any(item => !_itemHelper.IsAttachmentAttached(item)); + var hasRegularItems = itemsMap.Values.Any(item => !itemHelper.IsAttachmentAttached(item)); // Process all items that are not attached, attachments; those are handled separately, by value. if (hasRegularItems) @@ -219,11 +218,11 @@ public class InsuranceController( } // Log the number of items marked for deletion, if any - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { if (toDelete.Any()) { - _logger.Debug($"Marked {toDelete.Count} items for deletion from insurance."); + logger.Debug($"Marked {toDelete.Count} items for deletion from insurance."); } } @@ -254,8 +253,8 @@ public class InsuranceController( // The parent (not the hideout) could not be found. Skip and warn. if (parentItem is null && insuredItem.ParentId != rootItemParentID) { - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + serverLocalisationService.GetText( "insurance-unable_to_find_parent_of_item", new { @@ -270,16 +269,16 @@ public class InsuranceController( } // Not attached to parent, skip - if (!_itemHelper.IsAttachmentAttached(insuredItem)) + if (!itemHelper.IsAttachmentAttached(insuredItem)) { continue; } // Make sure the template for the item exists. - if (!_itemHelper.GetItem(insuredItem.Template).Key) + if (!itemHelper.GetItem(insuredItem.Template).Key) { - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + serverLocalisationService.GetText( "insurance-unable_to_find_attachment_in_db", new { @@ -293,12 +292,12 @@ public class InsuranceController( } // Get the main parent of this attachment. (e.g., The gun that this suppressor is attached to.) - var mainParent = _itemHelper.GetAttachmentMainParent(insuredItem.Id, itemsMap); + var mainParent = itemHelper.GetAttachmentMainParent(insuredItem.Id, itemsMap); if (mainParent is null) { // Odd. The parent couldn't be found. Skip this attachment and warn. - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + serverLocalisationService.GetText( "insurance-unable_to_find_main_parent_for_attachment", new { @@ -363,7 +362,7 @@ public class InsuranceController( } } - if (_itemHelper.IsRaidModdable(attachment, attachmentParentItem) ?? false) + if (itemHelper.IsRaidModdable(attachment, attachmentParentItem) ?? false) { moddableAttachments.Add(attachment); } @@ -396,7 +395,7 @@ public class InsuranceController( foreach (var insuredItem in insured.Items) { // Skip if the item is an attachment. These are handled separately. - if (_itemHelper.IsAttachmentAttached(insuredItem)) + if (itemHelper.IsAttachmentAttached(insuredItem)) { continue; } @@ -456,10 +455,10 @@ public class InsuranceController( // Log the parent item's name. itemsMap.TryGetValue(parentObj.Key, out var parentItem); - var parentName = _itemHelper.GetItemName(parentItem.Template); - if (_logger.IsLogEnabled(LogLevel.Debug)) + var parentName = itemHelper.GetItemName(parentItem.Template); + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug($"Processing attachments of parent {parentName}"); + logger.Debug($"Processing attachments of parent {parentName}"); } // Process the attachments for this individual parent item. @@ -492,7 +491,7 @@ public class InsuranceController( ); // Create prob array and add all attachments with rouble price as the weight - var attachmentsProbabilityArray = new ProbabilityObjectArray(_cloner); + var attachmentsProbabilityArray = new ProbabilityObjectArray(cloner); foreach (var (itemTpl, price) in weightedAttachmentByPrice) { attachmentsProbabilityArray.Add( @@ -512,9 +511,9 @@ public class InsuranceController( LogAttachmentsBeingRemoved(attachmentIdsToRemove, attachments, weightedAttachmentByPrice); - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug($"Number of attachments to be deleted: {attachmentIdsToRemove.Count}"); + logger.Debug($"Number of attachments to be deleted: {attachmentIdsToRemove.Count}"); } } @@ -533,9 +532,9 @@ public class InsuranceController( var index = 1; foreach (var attachmentId in attachmentIdsToRemove) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Attachment {index} Id: {attachmentId} Tpl: {attachments.FirstOrDefault(x => x.Id == attachmentId)?.Template} - " + $"Price: {attachmentPrices[attachmentId]}" ); @@ -557,17 +556,14 @@ public class InsuranceController( // Get a dictionary of item tpls + their rouble price foreach (var attachment in attachments) { - var price = _ragfairPriceService.GetDynamicItemPrice( - attachment.Template, - Money.ROUBLES - ); + var price = ragfairPriceService.GetDynamicItemPrice(attachment.Template, Money.ROUBLES); if (price is not null) { result[attachment.Id] = Math.Round(price ?? 0); } } - _weightedRandomHelper.ReduceWeightValues(result); + weightedRandomHelper.ReduceWeightValues(result); return result; } @@ -585,7 +581,7 @@ public class InsuranceController( { const int removeCount = 0; - if (_randomUtil.GetChance100(_insuranceConfig.ChanceNoAttachmentsTakenPercent)) + if (randomUtil.GetChance100(_insuranceConfig.ChanceNoAttachmentsTakenPercent)) { return removeCount; } @@ -613,11 +609,11 @@ public class InsuranceController( /// /// Profile that should receive the insurance message /// context of insurance to use - protected void SendMail(string sessionId, Insurance insurance) + protected void SendMail(MongoId sessionId, Insurance insurance) { // If there are no items remaining after the item filtering, the insurance has // successfully "failed" to return anything and an appropriate message should be sent to the player. - var traderDialogMessages = _databaseService.GetTrader(insurance.TraderId).Dialogue; + var traderDialogMessages = databaseService.GetTrader(insurance.TraderId).Dialogue; // Map is labs + insurance is disabled in base.json if (IsMapLabsAndInsuranceDisabled(insurance)) @@ -640,12 +636,12 @@ public class InsuranceController( ) ) { - insurance.MessageTemplateId = _randomUtil.GetArrayValue(insuranceFailedTemplates); + insurance.MessageTemplateId = randomUtil.GetArrayValue(insuranceFailedTemplates); } } // Send the insurance message - _mailSendService.SendLocalisedNpcMessageToPlayer( + mailSendService.SendLocalisedNpcMessageToPlayer( sessionId, insurance.TraderId, insurance.MessageType ?? MessageType.SystemMessage, @@ -670,7 +666,7 @@ public class InsuranceController( StringComparison.OrdinalIgnoreCase ) && !( - _databaseService.GetLocation(labsId)?.Base?.Insurance.GetValueOrDefault(false) + databaseService.GetLocation(labsId)?.Base?.Insurance.GetValueOrDefault(false) ?? false ); } @@ -692,7 +688,7 @@ public class InsuranceController( StringComparison.OrdinalIgnoreCase ) && !( - _databaseService.GetLocation(labyrinthId)?.Base?.Insurance.GetValueOrDefault(false) + databaseService.GetLocation(labyrinthId)?.Base?.Insurance.GetValueOrDefault(false) ?? false ); } @@ -713,7 +709,7 @@ public class InsuranceController( ? traderDialogMessages["insuranceFailedLabs"] : traderDialogMessages["insuranceFailed"]; - insurance.MessageTemplateId = _randomUtil.GetArrayValue(responseMesageIds); + insurance.MessageTemplateId = randomUtil.GetArrayValue(responseMesageIds); // Remove all insured items taken into labs insurance.Items = []; @@ -735,7 +731,7 @@ public class InsuranceController( ? traderDialogMessages["insuranceFailedLabyrinth"] : traderDialogMessages["insuranceFailed"]; - insurance.MessageTemplateId = _randomUtil.GetArrayValue(responseMessageIds); + insurance.MessageTemplateId = randomUtil.GetArrayValue(responseMessageIds); // Remove all insured items taken into labs insurance.Items = []; @@ -747,9 +743,9 @@ public class InsuranceController( /// Trader item was insured with /// Item being rolled on /// Should item be deleted - protected bool? RollForDelete(string traderId, Item? insuredItem = null) + protected bool? RollForDelete(MongoId traderId, Item? insuredItem = null) { - var trader = _traderStore.GetTraderById(traderId); + var trader = traderStore.GetTraderById(traderId); if (trader is null) { return null; @@ -758,18 +754,18 @@ public class InsuranceController( const int maxRoll = 9999; const int conversionFactor = 100; - var returnChance = _randomUtil.GetInt(0, maxRoll) / conversionFactor; + var returnChance = randomUtil.GetInt(0, maxRoll) / conversionFactor; var traderReturnChance = _insuranceConfig.ReturnChancePercent[traderId]; var roll = returnChance >= traderReturnChance; // Log the roll with as much detail as possible. var itemName = insuredItem is not null - ? $"{_itemHelper.GetItemName(insuredItem.Template)}" + ? $"{itemHelper.GetItemName(insuredItem.Template)}" : ""; var status = roll ? "Delete" : "Keep"; - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Rolling {itemName} with {trader} - Return {traderReturnChance}% - Roll: {returnChance} - Status: {status}" ); } @@ -787,10 +783,10 @@ public class InsuranceController( public ItemEventRouterResponse Insure( PmcData pmcData, InsureRequestData request, - string sessionId + MongoId sessionId ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); var itemsToInsureCount = request.Items.Count; List itemsToPay = []; @@ -804,7 +800,7 @@ public class InsuranceController( new IdWithCount { Id = Money.ROUBLES, // TODO: update to handle different currencies - Count = _insuranceService.GetRoublePriceToInsureItemWithTrader( + Count = insuranceService.GetRoublePriceToInsureItemWithTrader( pmcData, inventoryItemsHash[key], request.TransactionId @@ -825,7 +821,7 @@ public class InsuranceController( }; // pay for the item insurance - _paymentService.PayMoney(pmcData, options, sessionId, output); + paymentService.PayMoney(pmcData, options, sessionId, output); if (output.Warnings?.Count > 0) { return output; @@ -839,15 +835,13 @@ public class InsuranceController( new InsuredItem { TId = request.TransactionId, ItemId = inventoryItemsHash[key].Id } ); // If Item is Helmet or Body Armour -> Handle insurance of soft inserts - if ( - _itemHelper.ArmorItemHasRemovableOrSoftInsertSlots(inventoryItemsHash[key].Template) - ) + if (itemHelper.ArmorItemHasRemovableOrSoftInsertSlots(inventoryItemsHash[key].Template)) { InsureSoftInserts(inventoryItemsHash[key], pmcData, request); } } - _profileHelper.AddSkillPointsToPlayer( + profileHelper.AddSkillPointsToPlayer( pmcData, SkillTypes.Charisma, itemsToInsureCount * 0.01 @@ -870,14 +864,14 @@ public class InsuranceController( { var softInsertSlots = pmcData.Inventory.Items.Where(item => item.ParentId == itemWithSoftInserts.Id - && _itemHelper.IsSoftInsertId(item.SlotId.ToLowerInvariant()) + && itemHelper.IsSoftInsertId(item.SlotId.ToLowerInvariant()) ); foreach (var softInsertSlot in softInsertSlots) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug($"SoftInsertSlots: {softInsertSlot.SlotId}"); + logger.Debug($"SoftInsertSlots: {softInsertSlot.SlotId}"); } pmcData.InsuredItems.Add( @@ -893,10 +887,10 @@ public class InsuranceController( /// request object /// Session/Player id /// GetInsuranceCostResponseData object to send to client - public GetInsuranceCostResponseData Cost(GetInsuranceCostRequestData request, string sessionId) + public GetInsuranceCostResponseData Cost(GetInsuranceCostRequestData request, MongoId sessionId) { var response = new GetInsuranceCostResponseData(); - var pmcData = _profileHelper.GetPmcProfile(sessionId); + var pmcData = profileHelper.GetPmcProfile(sessionId); // Create hash of inventory items, keyed by item Id pmcData.Inventory.Items ??= []; @@ -911,9 +905,9 @@ public class InsuranceController( // Ensure hash has item in it if (!inventoryItemsHash.ContainsKey(itemId)) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Item with id: {itemId} missing from player inventory, skipping" ); } @@ -923,7 +917,7 @@ public class InsuranceController( items.TryAdd( inventoryItemsHash[itemId].Template, - _insuranceService.GetRoublePriceToInsureItemWithTrader( + insuranceService.GetRoublePriceToInsureItemWithTrader( pmcData, inventoryItemsHash[itemId], trader diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs index c7d64c64..1ed9b03d 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs @@ -18,22 +18,22 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class InventoryController( - ISptLogger _logger, - HttpResponseUtil _httpResponseUtil, - PresetHelper _presetHelper, - InventoryHelper _inventoryHelper, - HideoutHelper _hideoutHelper, - ProfileHelper _profileHelper, - TraderHelper _traderHelper, - ItemHelper _itemHelper, - DatabaseService _databaseService, - FenceService _fenceService, - RagfairOfferService _ragfairOfferService, - MapMarkerService _mapMarkerService, - ServerLocalisationService _serverLocalisationService, - LootGenerator _lootGenerator, - EventOutputHolder _eventOutputHolder, - ICloner _cloner + ISptLogger logger, + HttpResponseUtil httpResponseUtil, + PresetHelper presetHelper, + InventoryHelper inventoryHelper, + HideoutHelper hideoutHelper, + ProfileHelper profileHelper, + TraderHelper traderHelper, + ItemHelper itemHelper, + DatabaseService databaseService, + FenceService fenceService, + RagfairOfferService ragfairOfferService, + MapMarkerService mapMarkerService, + ServerLocalisationService serverLocalisationService, + LootGenerator lootGenerator, + EventOutputHolder eventOutputHolder, + ICloner cloner ) { /// @@ -47,7 +47,7 @@ public class InventoryController( public void MoveItem( PmcData pmcData, InventoryMoveRequestData moveRequest, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { @@ -57,7 +57,7 @@ public class InventoryController( } // Changes made to result apply to character inventory - var ownerInventoryItems = _inventoryHelper.GetOwnerInventoryItems( + var ownerInventoryItems = inventoryHelper.GetOwnerInventoryItems( moveRequest, moveRequest.Item, sessionId @@ -87,7 +87,7 @@ public class InventoryController( var originalLocationSlotId = originalItemLocation.SlotId; - var moveResult = _inventoryHelper.MoveItemInternal( + var moveResult = inventoryHelper.MoveItemInternal( pmcData, ownerInventoryItems.From ?? [], moveRequest, @@ -95,7 +95,7 @@ public class InventoryController( ); if (!moveResult) { - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } @@ -114,12 +114,12 @@ public class InventoryController( ) ) { - _hideoutHelper.ApplyPlaceOfFameDogtagBonus(pmcData); + hideoutHelper.ApplyPlaceOfFameDogtagBonus(pmcData); } } else { - _inventoryHelper.MoveItemToProfile( + inventoryHelper.MoveItemToProfile( ownerInventoryItems.From ?? [], ownerInventoryItems.To ?? [], moveRequest @@ -133,9 +133,9 @@ public class InventoryController( /// Item event router response protected void AppendTraderExploitErrorResponse(ItemEventRouterResponse output) { - _httpResponseUtil.AppendErrorToOutput( + httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText("inventory-edit_trader_item"), + serverLocalisationService.GetText("inventory-edit_trader_item"), (BackendErrorCodes)228 ); } @@ -151,7 +151,7 @@ public class InventoryController( public void PinOrLock( PmcData pmcData, PinOrLockItemRequest request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { @@ -160,7 +160,7 @@ public class InventoryController( ); if (itemToAdjust is null) { - _logger.Error( + logger.Error( $"Unable find item: {request.Item.Value.ToString()} to: {request.State} on player: {sessionId} to: " ); @@ -195,10 +195,10 @@ public class InventoryController( public void RedeemProfileReward( PmcData pmcData, RedeemProfileRequestData request, - string sessionId + MongoId sessionId ) { - var fullProfile = _profileHelper.GetFullProfile(sessionId); + var fullProfile = profileHelper.GetFullProfile(sessionId); foreach (var rewardEvent in request.Events) { // Hard coded to `SYSTEM` for now @@ -215,23 +215,23 @@ public class InventoryController( { case "TraderSalesSum": pmcData.TradersInfo[mailEvent.Entity].SalesSum = mailEvent.Value; - _traderHelper.LevelUp(mailEvent.Entity, pmcData); - _logger.Success( + traderHelper.LevelUp(mailEvent.Entity, pmcData); + logger.Success( $"Set trader {mailEvent.Entity}: Sales Sum to: {mailEvent.Value}" ); break; case "TraderStanding": pmcData.TradersInfo[mailEvent.Entity].Standing = mailEvent.Value; - _traderHelper.LevelUp(mailEvent.Entity, pmcData); - _logger.Success( + traderHelper.LevelUp(mailEvent.Entity, pmcData); + logger.Success( $"Set trader {mailEvent.Entity}: Standing to: {mailEvent.Value}" ); break; case "ProfileLevel": pmcData.Info.Experience = (int)mailEvent.Value.Value; // Will calculate level below - _traderHelper.ValidateTraderStandingsAndPlayerLevelForProfile(sessionId); - _logger.Success($"Set profile xp to: {mailEvent.Value}"); + traderHelper.ValidateTraderStandingsAndPlayerLevelForProfile(sessionId); + logger.Success($"Set profile xp to: {mailEvent.Value}"); break; case "SkillPoints": { @@ -240,31 +240,31 @@ public class InventoryController( ); if (profileSkill is null) { - _logger.Warning($"Unable to find skill with name: {mailEvent.Entity}"); + logger.Warning($"Unable to find skill with name: {mailEvent.Entity}"); continue; } profileSkill.Progress = mailEvent.Value; - _logger.Success($"Set profile skill: {mailEvent.Entity} to: {mailEvent.Value}"); + logger.Success($"Set profile skill: {mailEvent.Entity} to: {mailEvent.Value}"); break; } case "ExamineAllItems": { - var itemsToInspect = _itemHelper.GetItems().Where(x => x.Type != "Node"); + var itemsToInspect = itemHelper.GetItems().Where(x => x.Type != "Node"); FlagItemsAsInspectedAndRewardXp(itemsToInspect.Select(x => x.Id), fullProfile); - _logger.Success($"Flagged {itemsToInspect.Count()} items as examined"); + logger.Success($"Flagged {itemsToInspect.Count()} items as examined"); break; } case "UnlockTrader": pmcData.TradersInfo[mailEvent.Entity].Unlocked = true; - _logger.Success($"Trader {mailEvent.Entity} Unlocked"); + logger.Success($"Trader {mailEvent.Entity} Unlocked"); break; case "AssortmentUnlockRule": fullProfile.SptData.BlacklistedItemTemplates ??= []; fullProfile.SptData.BlacklistedItemTemplates.Add(mailEvent.Entity); - _logger.Success($"Item {mailEvent.Entity} is now blacklisted"); + logger.Success($"Item {mailEvent.Entity} is now blacklisted"); break; case "HideoutAreaLevel": @@ -284,7 +284,7 @@ public class InventoryController( break; } default: - _logger.Warning($"Unhandled profile reward event: {mailEvent.Type}"); + logger.Warning($"Unhandled profile reward event: {mailEvent.Type}"); break; } @@ -303,11 +303,11 @@ public class InventoryController( { foreach (var itemTpl in itemTpls) { - var item = _itemHelper.GetItem(itemTpl); + var item = itemHelper.GetItem(itemTpl); if (!item.Key) { - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + serverLocalisationService.GetText( "inventory-unable_to_inspect_item_not_in_db", itemTpl ) @@ -328,7 +328,7 @@ public class InventoryController( } // TODO: update this with correct calculation using values from globals json - _profileHelper.AddSkillPointsToPlayer( + profileHelper.AddSkillPointsToPlayer( fullProfile.CharacterData.PmcData, SkillTypes.Intellect, 0.05 * itemTpls.Count() @@ -346,13 +346,13 @@ public class InventoryController( public void OpenRandomLootContainer( PmcData pmcData, OpenRandomLootContainerRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { // Container player opened in their inventory var openedItem = pmcData.Inventory.Items.FirstOrDefault(item => item.Id == request.Item); - var containerDetailsDb = _itemHelper.GetItem(openedItem.Template); + var containerDetailsDb = itemHelper.GetItem(openedItem.Template); var isSealedWeaponBox = containerDetailsDb.Value.Name.Contains("event_container_airdrop"); var foundInRaid = openedItem.Upd?.SpawnedInSession; @@ -366,8 +366,8 @@ public class InventoryController( // Temp fix for unlocked weapon crate hideout craft if (isSealedWeaponBox || unlockedWeaponCrates.Contains(containerDetailsDb.Value.Id)) { - var containerSettings = _inventoryHelper.GetInventoryConfig().SealedAirdropContainer; - rewards.AddRange(_lootGenerator.GetSealedWeaponCaseLoot(containerSettings)); + var containerSettings = inventoryHelper.GetInventoryConfig().SealedAirdropContainer; + rewards.AddRange(lootGenerator.GetSealedWeaponCaseLoot(containerSettings)); if (containerSettings.FoundInRaid) { @@ -376,18 +376,18 @@ public class InventoryController( } else { - var rewardContainerDetails = _inventoryHelper.GetRandomLootContainerRewardDetails( + var rewardContainerDetails = inventoryHelper.GetRandomLootContainerRewardDetails( openedItem.Template ); if (rewardContainerDetails?.RewardCount == null) { - _logger.Error( + logger.Error( $"Unable to add loot to container: {openedItem.Template}, no rewards found" ); } else { - rewards.AddRange(_lootGenerator.GetRandomLootContainerLoot(rewardContainerDetails)); + rewards.AddRange(lootGenerator.GetRandomLootContainerLoot(rewardContainerDetails)); if (rewardContainerDetails.FoundInRaid) { @@ -406,7 +406,7 @@ public class InventoryController( Callback = null, UseSortingTable = true, }; - _inventoryHelper.AddItemsToStash(sessionId, addItemsRequest, pmcData, output); + inventoryHelper.AddItemsToStash(sessionId, addItemsRequest, pmcData, output); if (output.Warnings?.Count > 0) { return; @@ -414,7 +414,7 @@ public class InventoryController( } // Find and delete opened container item from player inventory - _inventoryHelper.RemoveItem(pmcData, request.Item, sessionId, output); + inventoryHelper.RemoveItem(pmcData, request.Item, sessionId, output); } /// @@ -427,11 +427,11 @@ public class InventoryController( public void EditMapMarker( PmcData pmcData, InventoryEditMarkerRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { - var mapItem = _mapMarkerService.EditMarkerOnMap(pmcData, request); + var mapItem = mapMarkerService.EditMarkerOnMap(pmcData, request); // sync with client output.ProfileChanges[sessionId].Items.ChangedItems.Add(mapItem); @@ -451,7 +451,7 @@ public class InventoryController( ItemEventRouterResponse output ) { - var mapItem = _mapMarkerService.DeleteMarkerFromMap(pmcData, request); + var mapItem = mapMarkerService.DeleteMarkerFromMap(pmcData, request); // sync with client output.ProfileChanges[sessionId].Items.ChangedItems.Add(mapItem); @@ -464,7 +464,7 @@ public class InventoryController( ItemEventRouterResponse output ) { - var adjustedMapItem = _mapMarkerService.CreateMarkerOnMap(pmcData, request); + var adjustedMapItem = mapMarkerService.CreateMarkerOnMap(pmcData, request); // Sync with client output.ProfileChanges[sessionId].Items.ChangedItems.Add(adjustedMapItem); @@ -480,7 +480,7 @@ public class InventoryController( public void SortInventory( PmcData pmcData, InventorySortRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { @@ -491,8 +491,8 @@ public class InventoryController( ); if (inventoryItem is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "inventory-unable_to_sort_inventory_restart_game", change.Id ) @@ -524,7 +524,7 @@ public class InventoryController( public ItemEventRouterResponse ReadEncyclopedia( PmcData pmcData, InventoryReadEncyclopediaRequestData request, - string sessionId + MongoId sessionId ) { foreach (var id in request.Ids) @@ -532,7 +532,7 @@ public class InventoryController( pmcData.Encyclopedia[id] = true; } - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -545,7 +545,7 @@ public class InventoryController( public void ExamineItem( PmcData pmcData, InventoryExamineRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { @@ -558,8 +558,8 @@ public class InventoryController( } catch { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "inventory-examine_item_does_not_exist", request.Item ) @@ -570,7 +570,7 @@ public class InventoryController( if (itemId is null) // item template { - if (_databaseService.GetItems().ContainsKey(request.Item)) + if (databaseService.GetItems().ContainsKey(request.Item)) { itemId = request.Item; } @@ -588,7 +588,7 @@ public class InventoryController( if (itemId is not null) { - var fullProfile = _profileHelper.GetFullProfile(sessionId); + var fullProfile = profileHelper.GetFullProfile(sessionId); FlagItemsAsInspectedAndRewardXp([itemId], fullProfile); } } @@ -599,17 +599,17 @@ public class InventoryController( /// /// Session/Player id /// Item tpl - protected MongoId? GetExaminedItemTpl(InventoryExamineRequestData request, string? sessionId) + protected MongoId? GetExaminedItemTpl(InventoryExamineRequestData request, MongoId sessionId) { - if (_presetHelper.IsPreset(request.Item)) + if (presetHelper.IsPreset(request.Item)) { - return _presetHelper.GetBaseItemTpl(request.Item); + return presetHelper.GetBaseItemTpl(request.Item); } if (request.FromOwner.Id == Traders.FENCE) // Get tpl from fence assorts { - return _fenceService + return fenceService .GetRawFenceAssorts() .Items.FirstOrDefault(x => x.Id == request.Item) ?.Template; @@ -619,7 +619,7 @@ public class InventoryController( // Not fence // get tpl from trader assort { - return _databaseService + return databaseService .GetTrader(request.FromOwner.Id) .Assort.Items.FirstOrDefault(item => item.Id == request.Item) ?.Template; @@ -628,7 +628,7 @@ public class InventoryController( if (request.FromOwner.Type == "RagFair") { // Try to get tplId from items.json first - var item = _itemHelper.GetItem(request.Item); + var item = itemHelper.GetItem(request.Item); if (item.Key) { return item.Value.Id; @@ -636,8 +636,8 @@ public class InventoryController( // Try alternate way of getting offer if first approach fails var offer = - _ragfairOfferService.GetOfferByOfferId(request.Item) - ?? _ragfairOfferService.GetOfferByOfferId(request.FromOwner.Id); + ragfairOfferService.GetOfferByOfferId(request.Item) + ?? ragfairOfferService.GetOfferByOfferId(request.FromOwner.Id); // Try find examine item inside offer items array var matchingItem = offer.Items.FirstOrDefault(offerItem => @@ -649,8 +649,8 @@ public class InventoryController( } // Unable to find item in database or ragfair - _logger.Warning( - _serverLocalisationService.GetText("inventory-unable_to_find_item", request.Item) + logger.Warning( + serverLocalisationService.GetText("inventory-unable_to_find_item", request.Item) ); } @@ -664,7 +664,7 @@ public class InventoryController( { // when inspecting an item in mail rewards, we are given on the message its in and its mongoId, not the Template, so we have to go find it ourselves // all mail the player has - var mail = _profileHelper.GetFullProfile(sessionId).DialogueRecords; + var mail = profileHelper.GetFullProfile(sessionId).DialogueRecords; // per trader/person mail var dialogue = mail.FirstOrDefault(x => x.Value.Messages.Any(m => m.Id == request.FromOwner.Id) @@ -680,7 +680,7 @@ public class InventoryController( } } - _logger.Error($"Unable to get item with id: {request.Item}"); + logger.Error($"Unable to get item with id: {request.Item}"); return null; } @@ -696,7 +696,7 @@ public class InventoryController( public void UnBindItem( PmcData pmcData, InventoryBindRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { @@ -717,7 +717,7 @@ public class InventoryController( public void BindItem( PmcData pmcData, InventoryBindRequestData bindRequest, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { @@ -741,13 +741,13 @@ public class InventoryController( public ItemEventRouterResponse TagItem( PmcData pmcData, InventoryTagRequestData request, - string sessionId + MongoId sessionId ) { var itemToTag = pmcData.Inventory.Items.FirstOrDefault(item => item.Id == request.Item); if (itemToTag is null) { - _logger.Warning( + logger.Warning( $"Unable to tag item: {request.Item} as it cannot be found in player {sessionId} inventory" ); @@ -759,7 +759,7 @@ public class InventoryController( itemToTag.Upd.Tag = new UpdTag { Color = request.TagColor, Name = request.TagName }; - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -772,7 +772,7 @@ public class InventoryController( public ItemEventRouterResponse ToggleItem( PmcData pmcData, InventoryToggleRequestData request, - string sessionId + MongoId sessionId ) { // May need to reassign to scav profile @@ -781,15 +781,15 @@ public class InventoryController( // Fix for toggling items while on they're in the Scav inventory if (request.FromOwner?.Type == "Profile" && request.FromOwner.Id != playerData.Id) { - playerData = _profileHelper.GetScavProfile(sessionId); + playerData = profileHelper.GetScavProfile(sessionId); } var itemToToggle = playerData.Inventory.Items.FirstOrDefault(x => x.Id == request.Item); if (itemToToggle is not null) { - _itemHelper.AddUpdObjectToItem( + itemHelper.AddUpdObjectToItem( itemToToggle, - _serverLocalisationService.GetText( + serverLocalisationService.GetText( "inventory-item_to_toggle_missing_upd", itemToToggle.Id ) @@ -797,11 +797,11 @@ public class InventoryController( itemToToggle.Upd.Togglable = new UpdTogglable { On = request.Value }; - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + serverLocalisationService.GetText( "inventory-unable_to_toggle_item_not_found", request.Item ) @@ -820,7 +820,7 @@ public class InventoryController( public ItemEventRouterResponse FoldItem( PmcData pmcData, InventoryFoldRequestData request, - string sessionId + MongoId sessionId ) { // May need to reassign to scav profile @@ -829,7 +829,7 @@ public class InventoryController( // We may be folding data on scav profile, get that profile instead if (request.FromOwner?.Type == "Profile" && request.FromOwner.Id != playerData.Id) { - playerData = _profileHelper.GetScavProfile(sessionId); + playerData = profileHelper.GetScavProfile(sessionId); } var itemToFold = playerData.Inventory.Items.FirstOrDefault(item => @@ -838,8 +838,8 @@ public class InventoryController( if (itemToFold is null) { // Item not found - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + serverLocalisationService.GetText( "inventory-unable_to_fold_item_not_found_in_inventory", request.Item ) @@ -849,11 +849,11 @@ public class InventoryController( } // Item may not have upd object - _itemHelper.AddUpdObjectToItem(itemToFold); + itemHelper.AddUpdObjectToItem(itemToFold); itemToFold.Upd.Foldable = new UpdFoldable { Folded = request.Value }; - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -868,21 +868,21 @@ public class InventoryController( public ItemEventRouterResponse SwapItem( PmcData pmcData, InventorySwapRequestData request, - string sessionId + MongoId sessionId ) { // During post-raid scav transfer, the swap may be in the scav inventory var playerData = pmcData; if (request.FromOwner?.Type == "Profile" && request.FromOwner.Id != playerData.Id) { - playerData = _profileHelper.GetScavProfile(sessionId); + playerData = profileHelper.GetScavProfile(sessionId); } var itemOne = playerData.Inventory.Items.FirstOrDefault(x => x.Id == request.Item); if (itemOne is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "inventory-unable_to_find_item_to_swap", new { item1Id = request.Item, item2Id = request.Item2 } ) @@ -892,8 +892,8 @@ public class InventoryController( var itemTwo = playerData.Inventory.Items.FirstOrDefault(x => x.Id == request.Item2); if (itemTwo is null) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "inventory-unable_to_find_item_to_swap", new { item1Id = request.Item2, item2Id = request.Item } ) @@ -928,7 +928,7 @@ public class InventoryController( } // Client already informed of inventory locations, nothing for us to do - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -943,12 +943,12 @@ public class InventoryController( public void TransferItem( PmcData pmcData, InventoryTransferRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { // TODO - check GetOwnerInventoryItems() call still works - var inventoryItems = _inventoryHelper.GetOwnerInventoryItems( + var inventoryItems = inventoryHelper.GetOwnerInventoryItems( request, request.Item, sessionId @@ -959,9 +959,9 @@ public class InventoryController( if (sourceItem is null) { var errorMessage = $"Unable to transfer stack, cannot find source: {request.Item}"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } @@ -969,9 +969,9 @@ public class InventoryController( if (destinationItem is null) { var errorMessage = $"Unable to transfer stack, cannot find destination: {request.With}"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } @@ -1007,12 +1007,12 @@ public class InventoryController( public void MergeItem( PmcData pmcData, InventoryMergeRequestData request, - string sessionID, + MongoId sessionID, ItemEventRouterResponse output ) { // Changes made to result apply to character inventory - var inventoryItems = _inventoryHelper.GetOwnerInventoryItems( + var inventoryItems = inventoryHelper.GetOwnerInventoryItems( request, request.Item, sessionID @@ -1024,9 +1024,9 @@ public class InventoryController( { var errorMessage = $"Unable to merge stacks as source item: {request.With} cannot be found"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } @@ -1037,9 +1037,9 @@ public class InventoryController( { var errorMessage = $"Unable to merge stacks as destination item: {request.With} cannot be found"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } @@ -1079,9 +1079,9 @@ public class InventoryController( { var errorMessage = $"Unable to find item: {sourceItem.Id} to remove from sender inventory"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } @@ -1099,12 +1099,12 @@ public class InventoryController( public void SplitItem( PmcData pmcData, InventorySplitRequestData request, - string sessionID, + MongoId sessionID, ItemEventRouterResponse output ) { // Changes made to result apply to character inventory - var inventoryItems = _inventoryHelper.GetOwnerInventoryItems( + var inventoryItems = inventoryHelper.GetOwnerInventoryItems( request, request.NewItem, sessionID @@ -1123,15 +1123,15 @@ public class InventoryController( { var errorMessage = $"Unable to split stack as source item: {request.SplitItem} cannot be found"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + httpResponseUtil.AppendErrorToOutput(output, errorMessage); return; } // Create new upd object that retains properties of original upd + new stack count size - var updatedUpd = _cloner.Clone(itemToSplit.Upd); + var updatedUpd = cloner.Clone(itemToSplit.Upd); updatedUpd.StackObjectsCount = request.Count; // Remove split item count from source stack @@ -1174,13 +1174,13 @@ public class InventoryController( public void DiscardItem( PmcData pmcData, InventoryRemoveRequestData request, - string sessionId, + MongoId sessionId, ItemEventRouterResponse output ) { if (request.FromOwner?.Type == "Mail") { - _inventoryHelper.RemoveItemAndChildrenFromMailRewards(sessionId, request, output); + inventoryHelper.RemoveItemAndChildrenFromMailRewards(sessionId, request, output); return; } @@ -1188,8 +1188,8 @@ public class InventoryController( var profileToRemoveItemFrom = request.FromOwner is null || request.FromOwner?.Id == pmcData.Id ? pmcData - : _profileHelper.GetFullProfile(sessionId).CharacterData.ScavData; + : profileHelper.GetFullProfile(sessionId).CharacterData.ScavData; - _inventoryHelper.RemoveItem(profileToRemoveItemFrom, request.Item, sessionId, output); + inventoryHelper.RemoveItem(profileToRemoveItemFrom, request.Item, sessionId, output); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs b/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs index 179246cb..9822dcc4 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs @@ -1,5 +1,6 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Launcher; using SPTarkov.Server.Core.Models.Eft.Profile; @@ -15,20 +16,18 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class LauncherController( - ISptLogger _logger, - IReadOnlyList _loadedMods, - HashUtil _hashUtil, - TimeUtil _timeUtil, - RandomUtil _randomUtil, - SaveServer _saveServer, - HttpServerHelper _httpServerHelper, - ProfileHelper _profileHelper, - DatabaseService _databaseService, - ServerLocalisationService _serverLocalisationService, - ConfigServer _configServer + ISptLogger logger, + IReadOnlyList loadedMods, + HashUtil hashUtil, + SaveServer saveServer, + HttpServerHelper httpServerHelper, + ProfileHelper profileHelper, + DatabaseService databaseService, + ServerLocalisationService serverLocalisationService, + ConfigServer configServer ) { - protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly CoreConfig _coreConfig = configServer.GetConfig(); /// /// Handle launcher connecting to server @@ -37,7 +36,7 @@ public class LauncherController( public ConnectResponse Connect() { // Get all possible profile types + filter out any that are blacklisted - var profileTemplates = _databaseService + var profileTemplates = databaseService .GetProfileTemplates() .Where(profile => !_coreConfig.Features.CreateNewProfileTypesBlacklist.Contains(profile.Key) @@ -46,7 +45,7 @@ public class LauncherController( return new ConnectResponse { - BackendUrl = _httpServerHelper.GetBackendUrl(), + BackendUrl = httpServerHelper.GetBackendUrl(), Name = _coreConfig.ServerName, Editions = profileTemplates.Select(x => x.Key).ToList(), ProfileDescriptions = GetProfileDescriptions(profileTemplates), @@ -67,7 +66,7 @@ public class LauncherController( { result.TryAdd( profileKey, - _serverLocalisationService.GetText(profile.DescriptionLocaleKey) + serverLocalisationService.GetText(profile.DescriptionLocaleKey) ); } @@ -78,11 +77,9 @@ public class LauncherController( /// /// Session/Player id /// - public Info? Find(string? sessionId) + public Info? Find(MongoId sessionId) { - return - sessionId is not null - && _saveServer.GetProfiles().TryGetValue(sessionId, out var profile) + return saveServer.GetProfiles().TryGetValue(sessionId, out var profile) ? profile.ProfileInfo : null; } @@ -91,9 +88,9 @@ public class LauncherController( /// /// /// - public string? Login(LoginRequestData? info) + public MongoId Login(LoginRequestData? info) { - foreach (var (sessionId, profile) in _saveServer.GetProfiles()) + foreach (var (sessionId, profile) in saveServer.GetProfiles()) { var account = profile.ProfileInfo; if (info?.Username == account?.Username) @@ -102,7 +99,7 @@ public class LauncherController( } } - return null; + return MongoId.Empty(); } /// @@ -111,7 +108,7 @@ public class LauncherController( /// public async Task Register(RegisterData info) { - foreach (var (_, profile) in _saveServer.GetProfiles()) + foreach (var (_, profile) in saveServer.GetProfiles()) { if (info.Username == profile.ProfileInfo?.Username) { @@ -126,62 +123,39 @@ public class LauncherController( /// /// /// - protected async Task CreateAccount(RegisterData info) + protected async Task CreateAccount(RegisterData info) { - var profileId = GenerateProfileId(); - var scavId = GenerateProfileId(); + var profileId = new MongoId(); + var scavId = new MongoId(); var newProfileDetails = new Info { ProfileId = profileId, ScavengerId = scavId, - Aid = _hashUtil.GenerateAccountId(), + Aid = hashUtil.GenerateAccountId(), Username = info.Username, Password = info.Password, IsWiped = true, Edition = info.Edition, }; - _saveServer.CreateProfile(newProfileDetails); + saveServer.CreateProfile(newProfileDetails); - await _saveServer.LoadProfileAsync(profileId); - await _saveServer.SaveProfileAsync(profileId); + await saveServer.LoadProfileAsync(profileId); + await saveServer.SaveProfileAsync(profileId); return profileId; } - /// - /// - /// - protected string GenerateProfileId() - { - var timestamp = _timeUtil.GetTimeStamp(); - - return FormatID(timestamp, timestamp * _randomUtil.GetInt(1, 1000000)); - } - - /// - /// - /// - /// - /// - protected string FormatID(long timeStamp, long counter) - { - var timeStampStr = Convert.ToString(timeStamp, 16).PadLeft(8, '0'); - var counterStr = Convert.ToString(counter, 16).PadLeft(16, '0'); - - return timeStampStr.ToLowerInvariant() + counterStr.ToLowerInvariant(); - } - /// /// /// /// - public string? ChangeUsername(ChangeRequestData info) + public MongoId ChangeUsername(ChangeRequestData info) { var sessionID = Login(info); - if (!string.IsNullOrEmpty(sessionID)) + if (!sessionID.IsEmpty()) { - _saveServer.GetProfile(sessionID).ProfileInfo!.Username = info.Change; + saveServer.GetProfile(sessionID).ProfileInfo!.Username = info.Change; } return sessionID; @@ -197,7 +171,7 @@ public class LauncherController( if (!string.IsNullOrEmpty(sessionID)) { - _saveServer.GetProfile(sessionID).ProfileInfo!.Password = info.Change; + saveServer.GetProfile(sessionID).ProfileInfo!.Password = info.Change; } return sessionID; @@ -208,23 +182,23 @@ public class LauncherController( /// /// Registration data /// Session id - public string? Wipe(RegisterData info) + public MongoId Wipe(RegisterData info) { if (!_coreConfig.AllowProfileWipe) { - return null; + return MongoId.Empty(); } - var sessionID = Login(info); + var sessionId = Login(info); - if (!string.IsNullOrEmpty(sessionID)) + if (!sessionId.IsEmpty()) { - var profileInfo = _saveServer.GetProfile(sessionID).ProfileInfo; + var profileInfo = saveServer.GetProfile(sessionId).ProfileInfo; profileInfo!.Edition = info.Edition; profileInfo.IsWiped = true; } - return sessionID; + return sessionId; } /// @@ -241,7 +215,7 @@ public class LauncherController( /// Dictionary of mod name and mod details public Dictionary GetLoadedServerMods() { - return _loadedMods.ToDictionary( + return loadedMods.ToDictionary( sptMod => sptMod.ModMetadata?.Name ?? "UNKNOWN MOD", sptMod => sptMod.ModMetadata ); @@ -252,9 +226,9 @@ public class LauncherController( /// /// Session/Player id /// Array of mod details - public List GetServerModsProfileUsed(string sessionId) + public List GetServerModsProfileUsed(MongoId sessionId) { - var profile = _profileHelper.GetFullProfile(sessionId); + var profile = profileHelper.GetFullProfile(sessionId); if (profile?.SptData?.Mods is not null) { diff --git a/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs b/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs index 37c9d75a..d1f0e068 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/LauncherV2Controller.cs @@ -1,4 +1,5 @@ using SPTarkov.DI.Annotations; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Launcher; using SPTarkov.Server.Core.Models.Eft.Profile; using SPTarkov.Server.Core.Models.Spt.Config; @@ -13,19 +14,17 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class LauncherV2Controller( - ISptLogger _logger, - IReadOnlyList _loadedMods, - HashUtil _hashUtil, - TimeUtil _timeUtil, - RandomUtil _randomUtil, - SaveServer _saveServer, - DatabaseService _databaseService, - ServerLocalisationService _serverLocalisationService, - ConfigServer _configServer, - Watermark _watermark + ISptLogger logger, + IReadOnlyList loadedMods, + HashUtil hashUtil, + SaveServer saveServer, + DatabaseService databaseService, + ServerLocalisationService serverLocalisationService, + ConfigServer configServer, + Watermark watermark ) { - protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly CoreConfig _coreConfig = configServer.GetConfig(); /// /// Returns a simple string of Pong! @@ -44,13 +43,13 @@ public class LauncherV2Controller( public Dictionary Types() { var result = new Dictionary(); - var dbProfiles = _databaseService.GetProfileTemplates(); + var dbProfiles = databaseService.GetProfileTemplates(); foreach (var profileKvP in dbProfiles) { result.TryAdd( profileKvP.Key, - _serverLocalisationService.GetText(profileKvP.Value.DescriptionLocaleKey) + serverLocalisationService.GetText(profileKvP.Value.DescriptionLocaleKey) ); } @@ -66,7 +65,7 @@ public class LauncherV2Controller( { var sessionId = GetSessionId(info); - return sessionId is not null; + return !sessionId.IsEmpty(); } /// @@ -76,7 +75,7 @@ public class LauncherV2Controller( /// public async Task Register(RegisterData info) { - foreach (var (_, profile) in _saveServer.GetProfiles()) + foreach (var (_, profile) in saveServer.GetProfiles()) { if (info.Username == profile.ProfileInfo!.Username) { @@ -97,7 +96,7 @@ public class LauncherV2Controller( { var sessionId = GetSessionId(info); - if (sessionId is null) + if (sessionId.IsEmpty()) { return false; } @@ -107,8 +106,8 @@ public class LauncherV2Controller( return false; } - _saveServer.GetProfile(sessionId).ProfileInfo!.Password = info.Change; - await _saveServer.SaveProfileAsync(sessionId); + saveServer.GetProfile(sessionId).ProfileInfo!.Password = info.Change; + await saveServer.SaveProfileAsync(sessionId); return true; } @@ -121,7 +120,7 @@ public class LauncherV2Controller( { var sessionId = GetSessionId(info); - return sessionId is not null && _saveServer.RemoveProfile(sessionId); + return !sessionId.IsEmpty() && saveServer.RemoveProfile(sessionId); } /// @@ -131,7 +130,7 @@ public class LauncherV2Controller( /// public string SptVersion() { - return _watermark.GetVersionTag(); + return watermark.GetVersionTag(); } /// @@ -150,7 +149,7 @@ public class LauncherV2Controller( /// public Dictionary LoadedMods() { - return _loadedMods.ToDictionary( + return loadedMods.ToDictionary( sptMod => sptMod.ModMetadata.Name, sptMod => sptMod.ModMetadata ); @@ -161,47 +160,32 @@ public class LauncherV2Controller( /// /// /// - protected async Task CreateAccount(RegisterData info) + protected async Task CreateAccount(RegisterData info) { - var profileId = GenerateProfileId(); - var scavId = GenerateProfileId(); + var profileId = new MongoId(); + var scavId = new MongoId(); var newProfileDetails = new Info { ProfileId = profileId, ScavengerId = scavId, - Aid = _hashUtil.GenerateAccountId(), + Aid = hashUtil.GenerateAccountId(), Username = info.Username, Password = info.Password, IsWiped = true, Edition = info.Edition, }; - _saveServer.CreateProfile(newProfileDetails); + saveServer.CreateProfile(newProfileDetails); - await _saveServer.LoadProfileAsync(profileId); - await _saveServer.SaveProfileAsync(profileId); + await saveServer.LoadProfileAsync(profileId); + await saveServer.SaveProfileAsync(profileId); return profileId; } - protected string GenerateProfileId() + protected MongoId GetSessionId(LoginRequestData info) { - var timestamp = _timeUtil.GetTimeStamp(); - - return FormatID(timestamp, timestamp * _randomUtil.GetInt(1, 1000000)); - } - - protected string FormatID(long timeStamp, long counter) - { - var timeStampStr = Convert.ToString(timeStamp, 16).PadLeft(8, '0'); - var counterStr = Convert.ToString(counter, 16).PadLeft(16, '0'); - - return timeStampStr.ToLowerInvariant() + counterStr.ToLowerInvariant(); - } - - protected string? GetSessionId(LoginRequestData info) - { - foreach (var (sessionId, profile) in _saveServer.GetProfiles()) + foreach (var (sessionId, profile) in saveServer.GetProfiles()) { if ( info.Username == profile.ProfileInfo!.Username @@ -212,11 +196,11 @@ public class LauncherV2Controller( } } - return null; + return MongoId.Empty(); } - public SptProfile GetProfile(string? sessionId) + public SptProfile GetProfile(MongoId sessionId) { - return _saveServer.GetProfile(sessionId); + return saveServer.GetProfile(sessionId); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/LocationController.cs b/Libraries/SPTarkov.Server.Core/Controllers/LocationController.cs index 4b67e721..155ad376 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/LocationController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/LocationController.cs @@ -11,9 +11,9 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class LocationController( - ISptLogger _logger, - DatabaseService _databaseService, - AirdropService _airdropService + ISptLogger logger, + DatabaseService databaseService, + AirdropService airdropService ) { /// @@ -22,9 +22,9 @@ public class LocationController( /// /// Players Id /// LocationsGenerateAllResponse - public LocationsGenerateAllResponse GenerateAll(string sessionId) + public LocationsGenerateAllResponse GenerateAll(MongoId sessionId) { - var locationsFromDb = _databaseService.GetLocations(); + var locationsFromDb = databaseService.GetLocations(); var maps = locationsFromDb.GetDictionary(); // keyed by _id location property @@ -35,9 +35,9 @@ public class LocationController( var mapBase = location.Base; if (mapBase == null) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug($"Map: {locationId} has no base json file, skipping generation"); + logger.Debug($"Map: {locationId} has no base json file, skipping generation"); } continue; @@ -65,9 +65,9 @@ public class LocationController( { if (request?.ContainerId is not null) { - return _airdropService.GenerateCustomAirdropLoot(request); + return airdropService.GenerateCustomAirdropLoot(request); } - return _airdropService.GenerateAirdropLoot(); + return airdropService.GenerateAirdropLoot(); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs b/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs index ab181745..8bff75fe 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/MatchController.cs @@ -1,5 +1,6 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Match; using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Utils; @@ -11,16 +12,16 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class MatchController( - ISptLogger _logger, - MatchLocationService _matchLocationService, - ConfigServer _configServer, - LocationLifecycleService _locationLifecycleService, - ProfileActivityService _profileActivityService, - WeatherHelper _weatherHelper + ISptLogger logger, + MatchLocationService matchLocationService, + ConfigServer configServer, + LocationLifecycleService locationLifecycleService, + ProfileActivityService profileActivityService, + WeatherHelper weatherHelper ) { - protected readonly MatchConfig _matchConfig = _configServer.GetConfig(); - protected readonly PmcConfig _pmcConfig = _configServer.GetConfig(); + protected readonly MatchConfig _matchConfig = configServer.GetConfig(); + protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); /// /// Handle client/match/available @@ -37,7 +38,7 @@ public class MatchController( /// Delete group request public void DeleteGroup(DeleteGroupRequest request) { - _matchLocationService.DeleteGroup(request); + matchLocationService.DeleteGroup(request); } /// @@ -46,7 +47,7 @@ public class MatchController( /// Start game request /// Session/Player id /// ProfileStatusResponse - public ProfileStatusResponse JoinMatch(MatchGroupJoinRequest request, string sessionId) + public ProfileStatusResponse JoinMatch(MatchGroupJoinRequest request, MongoId sessionId) { var output = new ProfileStatusResponse { @@ -90,13 +91,13 @@ public class MatchController( /// /// /// Session/Player id - public void ConfigureOfflineRaid(GetRaidConfigurationRequestData request, string sessionId) + public void ConfigureOfflineRaid(GetRaidConfigurationRequestData request, MongoId sessionId) { // set IsNightRaid to use it later for bot inventory generation - request.IsNightRaid = _weatherHelper.IsNightTime(request.TimeVariant, request.Location); + request.IsNightRaid = weatherHelper.IsNightTime(request.TimeVariant, request.Location); // Store request data for access during bot generation - _profileActivityService.GetProfileActivityRaidData(sessionId).RaidConfiguration = request; + profileActivityService.GetProfileActivityRaidData(sessionId).RaidConfiguration = request; // TODO: add code to strip PMC of equipment now they've started the raid @@ -132,11 +133,11 @@ public class MatchController( /// Start raid request /// StartLocalRaidResponseData public StartLocalRaidResponseData StartLocalRaid( - string sessionId, + MongoId sessionId, StartLocalRaidRequestData request ) { - return _locationLifecycleService.StartLocalRaid(sessionId, request); + return locationLifecycleService.StartLocalRaid(sessionId, request); } /// @@ -144,8 +145,8 @@ public class MatchController( /// /// Session/Player id /// Emd local raid request - public void EndLocalRaid(string sessionId, EndLocalRaidRequestData request) + public void EndLocalRaid(MongoId sessionId, EndLocalRaidRequestData request) { - _locationLifecycleService.EndLocalRaid(sessionId, request); + locationLifecycleService.EndLocalRaid(sessionId, request); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/NoteController.cs b/Libraries/SPTarkov.Server.Core/Controllers/NoteController.cs index d87b1860..4ae2a6c0 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/NoteController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/NoteController.cs @@ -1,4 +1,5 @@ using SPTarkov.DI.Annotations; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common; using SPTarkov.Server.Core.Models.Eft.ItemEvent; using SPTarkov.Server.Core.Models.Eft.Notes; @@ -7,7 +8,7 @@ using SPTarkov.Server.Core.Routers; namespace SPTarkov.Server.Core.Controllers; [Injectable] -public class NoteController(EventOutputHolder _eventOutputHolder) +public class NoteController(EventOutputHolder eventOutputHolder) { /// /// @@ -18,13 +19,13 @@ public class NoteController(EventOutputHolder _eventOutputHolder) public ItemEventRouterResponse AddNote( PmcData pmcData, NoteActionRequest request, - string sessionId + MongoId sessionId ) { var newNote = new Note { Time = request.Note.Time, Text = request.Note.Text }; pmcData.Notes.DataNotes.Add(newNote); - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -36,14 +37,14 @@ public class NoteController(EventOutputHolder _eventOutputHolder) public ItemEventRouterResponse EditNote( PmcData pmcData, NoteActionRequest request, - string sessionId + MongoId sessionId ) { var noteToEdit = pmcData.Notes.DataNotes[request.Index!.Value]; noteToEdit.Time = request.Note.Time; noteToEdit.Text = request.Note.Text; - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -55,11 +56,11 @@ public class NoteController(EventOutputHolder _eventOutputHolder) public ItemEventRouterResponse DeleteNote( PmcData pmcData, NoteActionRequest request, - string sessionId + MongoId sessionId ) { pmcData.Notes?.DataNotes?.RemoveAt(request.Index!.Value); - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/NotifierController.cs b/Libraries/SPTarkov.Server.Core/Controllers/NotifierController.cs index f7def4e9..3d2b5510 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/NotifierController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/NotifierController.cs @@ -1,5 +1,6 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Notifier; using SPTarkov.Server.Core.Models.Eft.Ws; using SPTarkov.Server.Core.Services; @@ -8,8 +9,8 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class NotifierController( - HttpServerHelper _httpServerHelper, - NotifierHelper _notifierHelper, + HttpServerHelper httpServerHelper, + NotifierHelper notifierHelper, NotificationService notificationService ) { @@ -23,7 +24,7 @@ public class NotifierController( /// If no notifications are available after the timeout, use a default message. /// /// Session/Player id - public Task> NotifyAsync(string sessionId) + public Task> NotifyAsync(MongoId sessionId) { return Task.Factory.StartNew(() => { @@ -46,7 +47,7 @@ public class NotifierController( } } - return [_notifierHelper.GetDefaultNotification()]; + return [notifierHelper.GetDefaultNotification()]; }); } @@ -55,15 +56,15 @@ public class NotifierController( /// /// Session/Player id /// NotifierChannel - public NotifierChannel GetChannel(string sessionId) + public NotifierChannel GetChannel(MongoId sessionId) { return new NotifierChannel { - Server = _httpServerHelper.BuildUrl(), + Server = httpServerHelper.BuildUrl(), ChannelId = sessionId, Url = "", NotifierServer = GetServer(sessionId), - WebSocket = _notifierHelper.GetWebSocketServer(sessionId), + WebSocket = notifierHelper.GetWebSocketServer(sessionId), }; } @@ -72,8 +73,8 @@ public class NotifierController( /// /// Session/Player id /// Notification server url - public string GetServer(string sessionId) + public string GetServer(MongoId sessionId) { - return $"{_httpServerHelper.GetBackendUrl()}/notifierServer/get/{sessionId}"; + return $"{httpServerHelper.GetBackendUrl()}/notifierServer/get/{sessionId.ToString()}"; } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/PresetController.cs b/Libraries/SPTarkov.Server.Core/Controllers/PresetController.cs index 349f6f09..ff62af6c 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/PresetController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/PresetController.cs @@ -9,9 +9,9 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class PresetController( - ISptLogger _logger, - PresetHelper _presetHelper, - DatabaseService _databaseService + ISptLogger logger, + PresetHelper presetHelper, + DatabaseService databaseService ) { /// @@ -19,13 +19,13 @@ public class PresetController( /// public void Initialize() { - var presets = _databaseService.GetGlobals().ItemPresets; + var presets = databaseService.GetGlobals().ItemPresets; var result = new Dictionary(); foreach (var (presetId, preset) in presets) { if (presetId != preset.Id) { - _logger.Error( + logger.Error( $"Preset for template tpl: '{preset.Items.FirstOrDefault()?.Template} {preset.Name}' has invalid key: ({presetId} != {preset.Id}). Skipping" ); @@ -45,6 +45,6 @@ public class PresetController( } } - _presetHelper.HydratePresetStore(result); + presetHelper.HydratePresetStore(result); } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/PrestigeController.cs b/Libraries/SPTarkov.Server.Core/Controllers/PrestigeController.cs index 1a531aa6..75eb3586 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/PrestigeController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/PrestigeController.cs @@ -1,5 +1,6 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Prestige; using SPTarkov.Server.Core.Models.Eft.Profile; @@ -11,10 +12,10 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class PrestigeController( - ISptLogger _logger, - ProfileHelper _profileHelper, - DatabaseService _databaseService, - SaveServer _saveServer + ISptLogger logger, + ProfileHelper profileHelper, + DatabaseService databaseService, + SaveServer saveServer ) { /// @@ -23,9 +24,9 @@ public class PrestigeController( /// /// Session/Player id /// Prestige - public Prestige GetPrestige(string sessionId) + public Prestige GetPrestige(MongoId sessionId) { - return _databaseService.GetTemplates().Prestige; + return databaseService.GetTemplates().Prestige; } /// @@ -58,9 +59,9 @@ public class PrestigeController( /// /// /// - public async Task ObtainPrestige(string sessionId, ObtainPrestigeRequestList request) + public async Task ObtainPrestige(MongoId sessionId, ObtainPrestigeRequestList request) { - var profile = _profileHelper.GetFullProfile(sessionId); + var profile = profileHelper.GetFullProfile(sessionId); if (profile is not null) { var pendingPrestige = new PendingPrestige @@ -72,7 +73,7 @@ public class PrestigeController( profile.SptData.PendingPrestige = pendingPrestige; profile.ProfileInfo.IsWiped = true; - await _saveServer.SaveProfileAsync(sessionId); + await saveServer.SaveProfileAsync(sessionId); } } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/ProfileController.cs b/Libraries/SPTarkov.Server.Core/Controllers/ProfileController.cs index fd51742d..0fc3820d 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/ProfileController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/ProfileController.cs @@ -2,6 +2,7 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Extensions; using SPTarkov.Server.Core.Generators; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Launcher; @@ -16,11 +17,11 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class ProfileController( - ISptLogger _logger, - SaveServer _saveServer, - CreateProfileService _createProfileService, - PlayerScavGenerator _playerScavGenerator, - ProfileHelper _profileHelper + ISptLogger logger, + SaveServer saveServer, + CreateProfileService createProfileService, + PlayerScavGenerator playerScavGenerator, + ProfileHelper profileHelper ) { /// @@ -29,7 +30,7 @@ public class ProfileController( /// public virtual List GetMiniProfiles() { - return _saveServer.GetProfiles().Select(kvp => GetMiniProfile(kvp.Key)).ToList(); + return saveServer.GetProfiles().Select(kvp => GetMiniProfile(kvp.Key)).ToList(); } /// @@ -37,9 +38,9 @@ public class ProfileController( /// /// Session/Player id /// - public virtual MiniProfile GetMiniProfile(string sessionId) + public virtual MiniProfile GetMiniProfile(MongoId sessionId) { - var profile = _saveServer.GetProfile(sessionId); + var profile = saveServer.GetProfile(sessionId); if (profile?.CharacterData == null) { throw new Exception( @@ -48,11 +49,11 @@ public class ProfileController( } var pmc = profile.CharacterData.PmcData; - var maxLvl = _profileHelper.GetMaxLevel(); + var maxLvl = profileHelper.GetMaxLevel(); // Player hasn't completed profile creation process, send defaults var currentLevel = pmc?.Info?.Level.GetValueOrDefault(1); - var xpToNextLevel = _profileHelper.GetExperience((currentLevel ?? 1) + 1); + var xpToNextLevel = profileHelper.GetExperience((currentLevel ?? 1) + 1); if (pmc?.Info?.Level == null) { return new MiniProfile @@ -68,7 +69,7 @@ public class ProfileController( MaxLevel = maxLvl, Edition = profile.ProfileInfo?.Edition ?? "", ProfileId = profile.ProfileInfo?.ProfileId ?? "", - SptData = _profileHelper.GetDefaultSptDataObject(), + SptData = profileHelper.GetDefaultSptDataObject(), }; } @@ -81,7 +82,7 @@ public class ProfileController( CurrentLevel = pmc.Info.Level, CurrentExperience = pmc.Info.Experience ?? 0, PreviousExperience = - currentLevel == 0 ? 0 : _profileHelper.GetExperience(currentLevel.Value), + currentLevel == 0 ? 0 : profileHelper.GetExperience(currentLevel.Value), NextLevel = xpToNextLevel, MaxLevel = maxLvl, Edition = profile.ProfileInfo?.Edition ?? "", @@ -95,9 +96,9 @@ public class ProfileController( /// /// Session/Player id /// Return a full profile, scav and pmc profiles + meta data - public virtual List GetCompleteProfile(string sessionId) + public virtual List GetCompleteProfile(MongoId sessionId) { - return _profileHelper.GetCompleteProfile(sessionId); + return profileHelper.GetCompleteProfile(sessionId); } /// @@ -108,10 +109,10 @@ public class ProfileController( /// Player id public virtual async ValueTask CreateProfile( ProfileCreateRequestData request, - string sessionId + MongoId sessionId ) { - return await _createProfileService.CreateProfile(sessionId, request); + return await createProfileService.CreateProfile(sessionId, request); } /// @@ -120,9 +121,9 @@ public class ProfileController( /// /// Player id /// PmcData - public virtual PmcData GeneratePlayerScav(string sessionId) + public virtual PmcData GeneratePlayerScav(MongoId sessionId) { - return _playerScavGenerator.Generate(sessionId); + return playerScavGenerator.Generate(sessionId); } /// @@ -133,7 +134,7 @@ public class ProfileController( /// public virtual NicknameValidationResult ValidateNickname( ValidateNicknameRequestData request, - string sessionId + MongoId sessionId ) { if (request.Nickname?.Length < 3) @@ -141,7 +142,7 @@ public class ProfileController( return NicknameValidationResult.Short; } - if (_profileHelper.IsNicknameTaken(request, sessionId)) + if (profileHelper.IsNicknameTaken(request, sessionId)) { return NicknameValidationResult.Taken; } @@ -158,7 +159,7 @@ public class ProfileController( /// public virtual NicknameValidationResult ChangeNickname( ProfileChangeNicknameRequestData request, - string sessionId + MongoId sessionId ) { var output = ValidateNickname( @@ -168,7 +169,7 @@ public class ProfileController( if (output == NicknameValidationResult.Valid) { - var pmcData = _profileHelper.GetPmcProfile(sessionId); + var pmcData = profileHelper.GetPmcProfile(sessionId); pmcData.Info.Nickname = request.Nickname; pmcData.Info.LowerNickname = request.Nickname.ToLowerInvariant(); @@ -182,9 +183,9 @@ public class ProfileController( /// /// Change voice request /// Player id - public virtual void ChangeVoice(ProfileChangeVoiceRequestData request, string sessionID) + public virtual void ChangeVoice(ProfileChangeVoiceRequestData request, MongoId sessionID) { - var pmcData = _profileHelper.GetPmcProfile(sessionID); + var pmcData = profileHelper.GetPmcProfile(sessionID); pmcData.Info.Voice = request.Voice; } @@ -196,13 +197,13 @@ public class ProfileController( /// Found profiles public virtual List SearchProfiles( SearchProfilesRequestData request, - string sessionID + MongoId sessionID ) { var result = new List(); // Find any profiles with a nickname containing the entered name - var allProfiles = _saveServer.GetProfiles().Values; + var allProfiles = saveServer.GetProfiles().Values; foreach (var profile in allProfiles) { @@ -215,7 +216,7 @@ public class ProfileController( continue; } - result.Add(_profileHelper.GetChatRoomMemberFromPmcProfile(pmcProfile)); + result.Add(profileHelper.GetChatRoomMemberFromPmcProfile(pmcProfile)); } return result; @@ -226,9 +227,9 @@ public class ProfileController( /// /// Session/Player id /// - public virtual GetProfileStatusResponseData GetProfileStatus(string sessionId) + public virtual GetProfileStatusResponseData GetProfileStatus(MongoId sessionId) { - var account = _saveServer.GetProfile(sessionId).ProfileInfo; + var account = saveServer.GetProfile(sessionId).ProfileInfo; var response = new GetProfileStatusResponseData { MaxPveCountExceeded = false, @@ -265,21 +266,21 @@ public class ProfileController( /// Get other profile request /// GetOtherProfileResponse public virtual GetOtherProfileResponse GetOtherProfile( - string sessionId, + MongoId sessionId, GetOtherProfileRequest request ) { // Find the profile by the account ID, fall back to the current player if we can't find the account - var profileToView = _profileHelper.GetFullProfileByAccountId(request.AccountId); + var profileToView = profileHelper.GetFullProfileByAccountId(request.AccountId); if ( profileToView?.CharacterData?.PmcData is null || profileToView.CharacterData.ScavData is null ) { - _logger.Warning( + logger.Warning( $"Unable to get profile: {request.AccountId} to show, falling back to own profile" ); - profileToView = _profileHelper.GetFullProfile(sessionId); + profileToView = profileHelper.GetFullProfile(sessionId); } var profileToViewPmc = profileToView.CharacterData.PmcData; @@ -335,7 +336,7 @@ public class ProfileController( Items = profileToViewPmc.Inventory.Items, }, Achievements = profileToViewPmc.Achievements, - FavoriteItems = _profileHelper.GetOtherProfileFavorites(profileToViewPmc), + FavoriteItems = profileHelper.GetOtherProfileFavorites(profileToViewPmc), PmcStats = new OtherProfileStats { Eft = new OtherProfileSubStats @@ -367,9 +368,9 @@ public class ProfileController( /// Session/Player id /// Get profile settings request /// - public virtual bool SetChosenProfileIcon(string sessionId, GetProfileSettingsRequest request) + public virtual bool SetChosenProfileIcon(MongoId sessionId, GetProfileSettingsRequest request) { - var profileToUpdate = _profileHelper.GetPmcProfile(sessionId); + var profileToUpdate = profileHelper.GetPmcProfile(sessionId); if (profileToUpdate == null) { return false; diff --git a/Libraries/SPTarkov.Server.Core/Controllers/QuestController.cs b/Libraries/SPTarkov.Server.Core/Controllers/QuestController.cs index 50d73890..d50b594d 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/QuestController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/QuestController.cs @@ -1,6 +1,7 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Extensions; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.ItemEvent; @@ -16,15 +17,15 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class QuestController( - ISptLogger _logger, - TimeUtil _timeUtil, - HttpResponseUtil _httpResponseUtil, - EventOutputHolder _eventOutputHolder, - MailSendService _mailSendService, - QuestHelper _questHelper, - QuestRewardHelper _questRewardHelper, - ServerLocalisationService _serverLocalisationService, - ICloner _cloner + ISptLogger logger, + TimeUtil timeUtil, + HttpResponseUtil httpResponseUtil, + EventOutputHolder eventOutputHolder, + MailSendService mailSendService, + QuestHelper questHelper, + QuestRewardHelper questRewardHelper, + ServerLocalisationService serverLocalisationService, + ICloner cloner ) { /// @@ -34,9 +35,9 @@ public class QuestController( /// /// Session/Player id /// Collection of Quest - public List GetClientQuests(string sessionId) + public List GetClientQuests(MongoId sessionId) { - return _questHelper.GetClientQuests(sessionId); + return questHelper.GetClientQuests(sessionId); } /// @@ -52,10 +53,10 @@ public class QuestController( public ItemEventRouterResponse AcceptQuest( PmcData pmcData, AcceptQuestRequestData acceptedQuest, - string sessionID + MongoId sessionID ) { - var acceptQuestResponse = _eventOutputHolder.GetOutput(sessionID); + var acceptQuestResponse = eventOutputHolder.GetOutput(sessionID); // Does quest exist in profile // Restarting a failed quest can mean quest exists in profile @@ -65,7 +66,7 @@ public class QuestController( if (existingQuestStatus is not null) { // Update existing - _questHelper.ResetQuestState(pmcData, QuestStatusEnum.Started, acceptedQuest.QuestId); + questHelper.ResetQuestState(pmcData, QuestStatusEnum.Started, acceptedQuest.QuestId); // Need to send client an empty list of completedConditions (Unsure if this does anything) acceptQuestResponse.ProfileChanges[sessionID].QuestsStatus.Add(existingQuestStatus); @@ -73,7 +74,7 @@ public class QuestController( else { // Add new quest to server profile - var newQuest = _questHelper.GetQuestReadyForProfile( + var newQuest = questHelper.GetQuestReadyForProfile( pmcData, QuestStatusEnum.Started, acceptedQuest @@ -83,7 +84,7 @@ public class QuestController( // Create a dialog message for starting the quest. // Note that for starting quests, the correct locale field is "description", not "startedMessageText". - var questFromDb = _questHelper.GetQuestFromDb(acceptedQuest.QuestId, pmcData); + var questFromDb = questHelper.GetQuestFromDb(acceptedQuest.QuestId, pmcData); if (questFromDb.Conditions?.AvailableForFinish is not null) { @@ -95,13 +96,13 @@ public class QuestController( } // Get messageId of text to send to player as text message in game - var messageId = _questHelper.GetMessageIdForQuestStart( + var messageId = questHelper.GetMessageIdForQuestStart( questFromDb.StartedMessageText, questFromDb.Description ); // Apply non-item rewards to profile + return item rewards - var startedQuestRewardItems = _questRewardHelper.ApplyQuestReward( + var startedQuestRewardItems = questRewardHelper.ApplyQuestReward( pmcData, acceptedQuest.QuestId, QuestStatusEnum.Started, @@ -110,19 +111,19 @@ public class QuestController( ); // Send started text + any starting reward items found above to player - _mailSendService.SendLocalisedNpcMessageToPlayer( + mailSendService.SendLocalisedNpcMessageToPlayer( sessionID, questFromDb.TraderId, MessageType.QuestStart, messageId, startedQuestRewardItems.ToList(), - _timeUtil.GetHoursAsSeconds( - (int)_questHelper.GetMailItemRedeemTimeHoursForProfile(pmcData) + timeUtil.GetHoursAsSeconds( + (int)questHelper.GetMailItemRedeemTimeHoursForProfile(pmcData) ) ); // Having accepted new quest, look for newly unlocked quests and inform client of them - var newlyAccessibleQuests = _questHelper.GetNewlyAccessibleQuestsWhenStartingQuest( + var newlyAccessibleQuests = questHelper.GetNewlyAccessibleQuestsWhenStartingQuest( acceptedQuest.QuestId, sessionID ); @@ -143,14 +144,14 @@ public class QuestController( protected void AddTaskConditionCountersToProfile( List questConditions, PmcData pmcData, - string questId + MongoId questId ) { foreach (var condition in questConditions) { if (pmcData.TaskConditionCounters.TryGetValue(condition.Id, out _)) { - _logger.Warning( + logger.Warning( $"Unable to add new task condition counter: {condition.ConditionType} for quest: {questId} to profile: {pmcData.SessionId} as it already exists" ); } @@ -183,10 +184,10 @@ public class QuestController( public ItemEventRouterResponse CompleteQuest( PmcData pmcData, CompleteQuestRequestData request, - string sessionId + MongoId sessionId ) { - return _questHelper.CompleteQuest(pmcData, request, sessionId); + return questHelper.CompleteQuest(pmcData, request, sessionId); } /// @@ -200,12 +201,12 @@ public class QuestController( public ItemEventRouterResponse HandoverQuest( PmcData pmcData, HandoverQuestRequestData request, - string sessionID + MongoId sessionID ) { - var quest = _questHelper.GetQuestFromDb(request.QuestId, pmcData); + var quest = questHelper.GetQuestFromDb(request.QuestId, pmcData); List handoverQuestTypes = ["HandoverItem", "WeaponAssembly"]; - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); var isItemHandoverQuest = true; var handedInCount = 0; @@ -234,8 +235,8 @@ public class QuestController( if (handedInCount <= 0) { - _logger.Error( - _serverLocalisationService.GetText( + logger.Error( + serverLocalisationService.GetText( "repeatable-quest_handover_failed_condition_already_satisfied", new { @@ -294,7 +295,7 @@ public class QuestController( if (itemHandover.Count - itemCountToRemove > 0) { // Remove single item with no children - _questHelper.ChangeItemStack( + questHelper.ChangeItemStack( pmcData, itemHandover.Id, (int)(itemHandover.Count - itemCountToRemove), @@ -326,7 +327,7 @@ public class QuestController( { if (toRemove.Contains(pmcData.Inventory.Items[index].Id)) { - var removedItem = _cloner.Clone(pmcData.Inventory.Items[index]); + var removedItem = cloner.Clone(pmcData.Inventory.Items[index]); pmcData.Inventory.Items.RemoveAt(index); // Remove the item @@ -370,18 +371,18 @@ public class QuestController( /// Client response /// ItemEventRouterResponse protected ItemEventRouterResponse ShowRepeatableQuestInvalidConditionError( - string questId, - string conditionId, + MongoId questId, + MongoId conditionId, ItemEventRouterResponse output ) { - var errorMessage = _serverLocalisationService.GetText( + var errorMessage = serverLocalisationService.GetText( "repeatable-quest_handover_failed_condition_invalid", new { questId, conditionId } ); - _logger.Error(errorMessage); + logger.Error(errorMessage); - return _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + return httpResponseUtil.AppendErrorToOutput(output, errorMessage); } /// @@ -399,7 +400,7 @@ public class QuestController( ItemEventRouterResponse output ) { - var errorMessage = _serverLocalisationService.GetText( + var errorMessage = serverLocalisationService.GetText( "quest-handover_wrong_item", new { @@ -408,9 +409,9 @@ public class QuestController( requiredTpl = handoverRequirements.Target.List.FirstOrDefault(), } ); - _logger.Error(errorMessage); + logger.Error(errorMessage); - return _httpResponseUtil.AppendErrorToOutput(output, errorMessage); + return httpResponseUtil.AppendErrorToOutput(output, errorMessage); } /// @@ -423,8 +424,8 @@ public class QuestController( /// Value to increment the backend counter with protected void UpdateProfileTaskConditionCounterValue( PmcData pmcData, - string conditionId, - string questId, + MongoId conditionId, + MongoId questId, double counterValue ) { @@ -458,11 +459,11 @@ public class QuestController( public ItemEventRouterResponse FailQuest( PmcData pmcData, FailQuestRequestData request, - string sessionID, + MongoId sessionID, ItemEventRouterResponse output ) { - _questHelper.FailQuest(pmcData, request, sessionID, output); + questHelper.FailQuest(pmcData, request, sessionID, output); return output; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs index 46e494e7..a1838685 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs @@ -21,106 +21,51 @@ using LogLevel = SPTarkov.Server.Core.Models.Spt.Logging.LogLevel; namespace SPTarkov.Server.Core.Controllers; [Injectable] -public class RagfairController +public class RagfairController( + ISptLogger logger, + TimeUtil timeUtil, + JsonUtil jsonUtil, + HttpResponseUtil httpResponseUtil, + EventOutputHolder eventOutputHolder, + RagfairServer ragfairServer, + ItemHelper itemHelper, + InventoryHelper inventoryHelper, + RagfairSellHelper ragfairSellHelper, + HandbookHelper handbookHelper, + ProfileHelper profileHelper, + PaymentHelper paymentHelper, + RagfairHelper ragfairHelper, + RagfairSortHelper ragfairSortHelper, + RagfairOfferHelper ragfairOfferHelper, + TraderHelper traderHelper, + DatabaseService databaseService, + ServerLocalisationService localisationService, + RagfairTaxService ragfairTaxService, + RagfairOfferService ragfairOfferService, + PaymentService paymentService, + RagfairPriceService ragfairPriceService, + RagfairOfferGenerator ragfairOfferGenerator, + ConfigServer configServer +) { - protected ConfigServer _configServer; - protected DatabaseService _databaseService; - protected EventOutputHolder _eventOutputHolder; - protected HandbookHelper _handbookHelper; - protected HttpResponseUtil _httpResponseUtil; - protected InventoryHelper _inventoryHelper; - protected ItemHelper _itemHelper; - protected JsonUtil _jsonUtil; - protected ServerLocalisationService _serverLocalisationService; - protected ISptLogger _logger; - protected PaymentHelper _paymentHelper; - protected PaymentService _paymentService; - protected ProfileHelper _profileHelper; - - protected RagfairConfig _ragfairConfig; - protected RagfairHelper _ragfairHelper; - protected RagfairOfferGenerator _ragfairOfferGenerator; - protected RagfairOfferHelper _ragfairOfferHelper; - protected RagfairOfferService _ragfairOfferService; - protected RagfairPriceService _ragfairPriceService; - protected RagfairSellHelper _ragfairSellHelper; - protected RagfairServer _ragfairServer; - protected RagfairSortHelper _ragfairSortHelper; - protected RagfairTaxService _ragfairTaxService; - protected TimeUtil _timeUtil; - protected TraderHelper _traderHelper; - - public RagfairController( - ISptLogger logger, - TimeUtil timeUtil, - JsonUtil jsonUtil, - HttpResponseUtil httpResponseUtil, - EventOutputHolder eventOutputHolder, - RagfairServer ragfairServer, - ItemHelper itemHelper, - InventoryHelper inventoryHelper, - RagfairSellHelper ragfairSellHelper, - HandbookHelper handbookHelper, - ProfileHelper profileHelper, - PaymentHelper paymentHelper, - RagfairHelper ragfairHelper, - RagfairSortHelper ragfairSortHelper, - RagfairOfferHelper ragfairOfferHelper, - TraderHelper traderHelper, - DatabaseService databaseService, - ServerLocalisationService localisationService, - RagfairTaxService ragfairTaxService, - RagfairOfferService ragfairOfferService, - PaymentService paymentService, - RagfairPriceService ragfairPriceService, - RagfairOfferGenerator ragfairOfferGenerator, - ConfigServer configServer - ) - { - _logger = logger; - _timeUtil = timeUtil; - _jsonUtil = jsonUtil; - _httpResponseUtil = httpResponseUtil; - _eventOutputHolder = eventOutputHolder; - _ragfairServer = ragfairServer; - _itemHelper = itemHelper; - _inventoryHelper = inventoryHelper; - _ragfairSellHelper = ragfairSellHelper; - _handbookHelper = handbookHelper; - _profileHelper = profileHelper; - _paymentHelper = paymentHelper; - _ragfairHelper = ragfairHelper; - _ragfairSortHelper = ragfairSortHelper; - _ragfairOfferHelper = ragfairOfferHelper; - _traderHelper = traderHelper; - _databaseService = databaseService; - _serverLocalisationService = localisationService; - _ragfairTaxService = ragfairTaxService; - _ragfairOfferService = ragfairOfferService; - _paymentService = paymentService; - _ragfairPriceService = ragfairPriceService; - _ragfairOfferGenerator = ragfairOfferGenerator; - _configServer = configServer; - - _ragfairConfig = _configServer.GetConfig(); - } + protected RagfairConfig _ragfairConfig = configServer.GetConfig(); /// /// Check all profiles and sell player offers / send player money for listing if it sold /// public void Update() { - foreach (var (sessionId, profile) in _profileHelper.GetProfiles()) + foreach (var (sessionId, profile) in profileHelper.GetProfiles()) { // Check profile is capable of creating offers var pmcProfile = profile.CharacterData.PmcData; if ( pmcProfile.RagfairInfo is not null && pmcProfile.Info.Level - >= _databaseService.GetGlobals().Configuration.RagFair.MinUserLevel + >= databaseService.GetGlobals().Configuration.RagFair.MinUserLevel ) { - _ragfairOfferHelper.ProcessOffersOnProfile(sessionId); + ragfairOfferHelper.ProcessOffersOnProfile(sessionId); } } } @@ -132,11 +77,11 @@ public class RagfairController /// Session/Player id /// Search request data from client /// Flea offers that match required search parameters - public GetOffersResult GetOffers(string sessionID, SearchRequestData searchRequest) + public GetOffersResult GetOffers(MongoId sessionID, SearchRequestData searchRequest) { - var profile = _profileHelper.GetFullProfile(sessionID); - var itemsToAdd = _ragfairHelper.FilterCategories(sessionID, searchRequest); - var traderAssorts = _ragfairHelper.GetDisplayableAssorts(sessionID); + var profile = profileHelper.GetFullProfile(sessionID); + var itemsToAdd = ragfairHelper.FilterCategories(sessionID, searchRequest); + var traderAssorts = ragfairHelper.GetDisplayableAssorts(sessionID); var result = new GetOffersResult { Offers = [], @@ -166,7 +111,7 @@ public class RagfairController AddIndexValueToOffers(result.Offers); // Sort offers - result.Offers = _ragfairSortHelper.SortOffers( + result.Offers = ragfairSortHelper.SortOffers( result.Offers, searchRequest.SortType.GetValueOrDefault(RagfairSort.ID), searchRequest.SortDirection.GetValueOrDefault(0) @@ -184,13 +129,13 @@ public class RagfairController // Update trader offers' values, Lock quest-linked offers + adjust offer buy limits foreach ( var traderOffer in result.Offers.Where(offer => - _ragfairOfferHelper.OfferIsFromTrader(offer) + ragfairOfferHelper.OfferIsFromTrader(offer) ) ) { // For the items, check the barter schemes. The method getDisplayableAssorts sets a flag sptQuestLocked // to true if the quest is not completed yet - if (_ragfairOfferHelper.TraderOfferItemQuestLocked(traderOffer, traderAssorts)) + if (ragfairOfferHelper.TraderOfferItemQuestLocked(traderOffer, traderAssorts)) { traderOffer.Locked = true; } @@ -231,7 +176,7 @@ public class RagfairController { // Occurs when player edits "item count shown per page" value when on page near end of offer list // The page no longer exists due to the larger number of items on each page, show them the very end of the offer list instead - _logger.Warning(_serverLocalisationService.GetText("ragfair-offer_page_doesnt_exist")); + logger.Warning(localisationService.GetText("ragfair-offer_page_doesnt_exist")); startIndex = result.Offers.Count - perPageLimit; endIndex = result.Offers.Count; } @@ -246,13 +191,13 @@ public class RagfairController private void SetTraderOfferStackSize(RagfairOffer offer) { var firstItem = offer.Items[0]; - var traderAssorts = _traderHelper.GetTraderAssortsByTraderId(offer.User.Id).Items; + var traderAssorts = traderHelper.GetTraderAssortsByTraderId(offer.User.Id).Items; var assortPurchased = traderAssorts?.FirstOrDefault(x => x.Id == offer.Items.First().Id); if (assortPurchased is null) { - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + localisationService.GetText( "ragfair-unable_to_adjust_stack_count_assort_not_found", new { offerId = offer.Items.First().Id, traderId = offer.User.Id } ) @@ -284,7 +229,7 @@ public class RagfairController // Not purchased by player before, use value from assort data // Find patching assort by its id - var traderAssorts = _traderHelper.GetTraderAssortsByTraderId(offer.User.Id).Items; + var traderAssorts = traderHelper.GetTraderAssortsByTraderId(offer.User.Id).Items; var assortData = traderAssorts.FirstOrDefault(item => item.Id == assortId); // Set restriction based on data found above @@ -333,7 +278,7 @@ public class RagfairController // Linked/required search categories var playerHasFleaUnlocked = pmcProfile.Info.Level - >= _databaseService.GetGlobals().Configuration.RagFair.MinUserLevel; + >= databaseService.GetGlobals().Configuration.RagFair.MinUserLevel; List offerPool = []; if (IsLinkedSearch(searchRequest) || IsRequiredSearch(searchRequest)) { @@ -342,20 +287,20 @@ public class RagfairController else if (!(IsLinkedSearch(searchRequest) || IsRequiredSearch(searchRequest))) { // Get all categories - offerPool = _ragfairOfferService.GetOffers(); + offerPool = ragfairOfferService.GetOffers(); } else { - _logger.Error(_serverLocalisationService.GetText("ragfair-unable_to_get_categories")); - if (_logger.IsLogEnabled(LogLevel.Debug)) + logger.Error(localisationService.GetText("ragfair-unable_to_get_categories")); + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug(_jsonUtil.Serialize(searchRequest)); + logger.Debug(jsonUtil.Serialize(searchRequest)); } return []; } - return _ragfairServer.GetAllActiveCategories( + return ragfairServer.GetAllActiveCategories( playerHasFleaUnlocked, searchRequest, offerPool @@ -400,7 +345,7 @@ public class RagfairController // Searching for items in preset menu if (searchRequest.BuildCount > 0) { - return _ragfairOfferHelper.GetOffersForBuild( + return ragfairOfferHelper.GetOffersForBuild( searchRequest, itemsToAdd, traderAssorts, @@ -410,11 +355,11 @@ public class RagfairController if (searchRequest.NeededSearchId?.Length > 0) { - return _ragfairOfferHelper.GetOffersThatRequireItem(searchRequest, pmcProfile); + return ragfairOfferHelper.GetOffersThatRequireItem(searchRequest, pmcProfile); } // Searching for general items - return _ragfairOfferHelper.GetValidOffers( + return ragfairOfferHelper.GetValidOffers( searchRequest, itemsToAdd, traderAssorts, @@ -434,7 +379,7 @@ public class RagfairController ) { // Get all items of tpl - var offers = _ragfairOfferService.GetOffersOfType(getPriceRequest.TemplateId); + var offers = ragfairOfferService.GetOffersOfType(getPriceRequest.TemplateId); // Offers exist for item, get averages of what's listed if (offers?.Count > 0) @@ -455,10 +400,10 @@ public class RagfairController // No offers listed, get price from live ragfair price list prices.json // No flea price, get handbook price - var fleaPrices = _databaseService.GetPrices(); + var fleaPrices = databaseService.GetPrices(); if (!fleaPrices.TryGetValue(getPriceRequest.TemplateId, out var tplPrice)) { - tplPrice = _handbookHelper.GetTemplatePrice(getPriceRequest.TemplateId); + tplPrice = handbookHelper.GetTemplatePrice(getPriceRequest.TemplateId); } return new GetItemPriceResult @@ -481,12 +426,12 @@ public class RagfairController foreach (var offer in offers) { // Exclude barter items, they tend to have outrageous equivalent prices - if (offer.Requirements.Any(req => !_paymentHelper.IsMoneyTpl(req.TemplateId))) + if (offer.Requirements.Any(req => !paymentHelper.IsMoneyTpl(req.TemplateId))) { continue; } - if (ignoreTraderOffers && _ragfairOfferHelper.OfferIsFromTrader(offer)) + if (ignoreTraderOffers && ragfairOfferHelper.OfferIsFromTrader(offer)) { continue; } @@ -529,15 +474,15 @@ public class RagfairController public ItemEventRouterResponse AddPlayerOffer( PmcData pmcData, AddOfferRequestData offerRequest, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); - var fullProfile = _profileHelper.GetFullProfile(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); + var fullProfile = profileHelper.GetFullProfile(sessionID); if (!IsValidPlayerOfferRequest(offerRequest)) { - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, "Unable to add offer, check server for error" ); @@ -546,7 +491,7 @@ public class RagfairController var typeOfOffer = GetOfferType(offerRequest); if (typeOfOffer == FleaOfferType.UNKNOWN) { - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, $"Unknown offer type: {typeOfOffer}, cannot list item on flea" ); @@ -562,7 +507,7 @@ public class RagfairController return CreatePackOffer(sessionID, offerRequest, fullProfile, output); case FleaOfferType.UNKNOWN: default: - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, $"Unknown offer type: {typeOfOffer}, cannot list item on flea" ); @@ -578,19 +523,15 @@ public class RagfairController { if (offerRequest?.Items is null || offerRequest.Items.Count == 0) { - _logger.Error( - _serverLocalisationService.GetText("ragfair-invalid_player_offer_request") - ); + logger.Error(localisationService.GetText("ragfair-invalid_player_offer_request")); return false; } if (offerRequest.Requirements is null) { - _logger.Error( - _serverLocalisationService.GetText( - "ragfair-unable_to_place_offer_with_no_requirements" - ) + logger.Error( + localisationService.GetText("ragfair-unable_to_place_offer_with_no_requirements") ); return false; @@ -640,7 +581,7 @@ public class RagfairController /// output Response to send to client /// ItemEventRouterResponse protected ItemEventRouterResponse CreateMultiOffer( - string sessionID, + MongoId sessionID, AddOfferRequestData offerRequest, SptProfile fullProfile, ItemEventRouterResponse output @@ -661,11 +602,11 @@ public class RagfairController var result = GetItemsToListOnFleaFromInventory(pmcData, offerRequest.Items); if (result.Items is null || !string.IsNullOrEmpty(result.ErrorMessage)) { - _httpResponseUtil.AppendErrorToOutput(output, result.ErrorMessage); + httpResponseUtil.AppendErrorToOutput(output, result.ErrorMessage); } // Total count of items summed using their individual stack counts - var stackCountTotal = _ragfairOfferHelper.GetTotalStackCountSize(result.Items); + var stackCountTotal = ragfairOfferHelper.GetTotalStackCountSize(result.Items); // When listing identical items on flea, condense separate items into one stack with a merged stack count // e.g. 2 ammo items each with stackObjectCount = 3, will result in 1 stack of 6 @@ -698,7 +639,7 @@ public class RagfairController } // Get average of item+children quality - var qualityMultiplier = _itemHelper.GetItemQualityModifierForItems(offer.Items, true); + var qualityMultiplier = itemHelper.GetItemQualityModifierForItems(offer.Items, true); // Multiply single item price by quality averageOfferPrice *= qualityMultiplier; @@ -707,14 +648,14 @@ public class RagfairController var playerListedPriceInRub = CalculateRequirementsPriceInRub(offerRequest.Requirements); // Roll sale chance - var sellChancePercent = _ragfairSellHelper.CalculateSellChance( + var sellChancePercent = ragfairSellHelper.CalculateSellChance( averageOfferPrice.Value, playerListedPriceInRub, qualityMultiplier ); // Create array of sell times for items listed - offer.SellResults = _ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal); + offer.SellResults = ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal); // Subtract flea market fee from stash if (_ragfairConfig.Sell.Fees) @@ -741,7 +682,7 @@ public class RagfairController // Remove items from inventory after creating offer foreach (var itemToRemove in offerRequest.Items) { - _inventoryHelper.RemoveItem(pmcData, itemToRemove, sessionID, output); + inventoryHelper.RemoveItem(pmcData, itemToRemove, sessionID, output); } return output; @@ -758,7 +699,7 @@ public class RagfairController /// Response to send to client /// ItemEventRouterResponse protected ItemEventRouterResponse CreatePackOffer( - string sessionID, + MongoId sessionID, AddOfferRequestData offerRequest, SptProfile fullProfile, ItemEventRouterResponse output @@ -777,11 +718,11 @@ public class RagfairController var result = GetItemsToListOnFleaFromInventory(pmcData, offerRequest.Items); if (result.Items is null || !string.IsNullOrEmpty(result.ErrorMessage)) { - _httpResponseUtil.AppendErrorToOutput(output, result.ErrorMessage); + httpResponseUtil.AppendErrorToOutput(output, result.ErrorMessage); } // Total count of items summed using their stack counts - var stackCountTotal = _ragfairOfferHelper.GetTotalStackCountSize(result.Items); + var stackCountTotal = ragfairOfferHelper.GetTotalStackCountSize(result.Items); // When listing identical items on flea, condense separate items into one stack with a merged stack count // e.g. 2 ammo items, stackObjectCount = 3 for each, will result in 1 stack of 6 @@ -819,7 +760,7 @@ public class RagfairController } // Get average of item+children quality - var qualityMultiplier = _itemHelper.GetItemQualityModifierForItems(offer.Items, true); + var qualityMultiplier = itemHelper.GetItemQualityModifierForItems(offer.Items, true); // Multiply single item price by quality singleItemPrice *= qualityMultiplier; @@ -828,14 +769,14 @@ public class RagfairController var playerListedPriceInRub = CalculateRequirementsPriceInRub(offerRequest.Requirements); // Roll sale chance - var sellChancePercent = _ragfairSellHelper.CalculateSellChance( + var sellChancePercent = ragfairSellHelper.CalculateSellChance( singleItemPrice.Value * stackCountTotal, playerListedPriceInRub, qualityMultiplier ); // Create array of sell times for items listed + sell all at once as it's a pack - offer.SellResults = _ragfairSellHelper.RollForSale( + offer.SellResults = ragfairSellHelper.RollForSale( sellChancePercent, (int)stackCountTotal, true @@ -866,7 +807,7 @@ public class RagfairController // Remove items from inventory after creating offer foreach (var itemToRemove in offerRequest.Items) { - _inventoryHelper.RemoveItem(pmcData, itemToRemove, sessionID, output); + inventoryHelper.RemoveItem(pmcData, itemToRemove, sessionID, output); } return output; @@ -882,7 +823,7 @@ public class RagfairController /// Response to send to client /// ItemEventRouterResponse protected ItemEventRouterResponse CreateSingleOffer( - string sessionID, + MongoId sessionID, AddOfferRequestData offerRequest, SptProfile fullProfile, ItemEventRouterResponse output @@ -898,15 +839,13 @@ public class RagfairController || !string.IsNullOrEmpty(inventoryItemsToSell.ErrorMessage) ) { - _httpResponseUtil.AppendErrorToOutput(output, inventoryItemsToSell.ErrorMessage); + httpResponseUtil.AppendErrorToOutput(output, inventoryItemsToSell.ErrorMessage); } var firstItemToSell = inventoryItemsToSell.Items.FirstOrDefault().FirstOrDefault(); // Total count of items summed using their stack counts - var stackCountTotal = _ragfairOfferHelper.GetTotalStackCountSize( - inventoryItemsToSell.Items - ); + var stackCountTotal = ragfairOfferHelper.GetTotalStackCountSize(inventoryItemsToSell.Items); // Average offer price for single item (or whole weapon) // MUST occur prior to CreatePlayerOffer(), otherwise offer ends up in averages calculation @@ -927,7 +866,7 @@ public class RagfairController var offerRootItem = offer.Items.FirstOrDefault(x => x.Id == offerRequest.Items[0]); // Get average of items quality+children - var qualityMultiplier = _itemHelper.GetItemQualityModifierForItems(offer.Items, true); + var qualityMultiplier = itemHelper.GetItemQualityModifierForItems(offer.Items, true); // Check for and apply item price modifer if it exists in config if ( @@ -944,12 +883,12 @@ public class RagfairController averageOfferPriceSingleItem *= qualityMultiplier; // Packs are reduced to the average price of a single item in the pack vs the averaged single price of an item - var sellChancePercent = _ragfairSellHelper.CalculateSellChance( + var sellChancePercent = ragfairSellHelper.CalculateSellChance( averageOfferPriceSingleItem.Value, playerListedPriceInRub, qualityMultiplier ); - offer.SellResults = _ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal); + offer.SellResults = ragfairSellHelper.RollForSale(sellChancePercent, (int)stackCountTotal); // Subtract flea market fee from stash if (_ragfairConfig.Sell.Fees) @@ -976,7 +915,7 @@ public class RagfairController // Remove items from inventory after creating offer foreach (var itemToRemove in offerRequest.Items) { - _inventoryHelper.RemoveItem(pmcData, itemToRemove, sessionID, output); + inventoryHelper.RemoveItem(pmcData, itemToRemove, sessionID, output); } return output; @@ -994,7 +933,7 @@ public class RagfairController /// ItemEventRouterResponse /// True if charging tax to player failed protected bool ChargePlayerTaxFee( - string sessionId, + MongoId sessionId, Item rootItem, PmcData pmcData, double requirementsPriceInRub, @@ -1004,12 +943,12 @@ public class RagfairController ) { // Get tax from cache hydrated earlier by client, if that's missing fall back to server calculation (inaccurate) - var storedClientTaxValue = _ragfairTaxService.GetStoredClientOfferTaxValueById( + var storedClientTaxValue = ragfairTaxService.GetStoredClientOfferTaxValueById( offerRequest.Items[0] ); var tax = storedClientTaxValue is not null ? storedClientTaxValue.Fee - : _ragfairTaxService.CalculateTax( + : ragfairTaxService.CalculateTax( rootItem, pmcData, requirementsPriceInRub, @@ -1017,23 +956,23 @@ public class RagfairController offerRequest.SellInOnePiece.GetValueOrDefault(false) ); - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug( + logger.Debug( $"Offer tax to charge: {tax}, pulled from client: {storedClientTaxValue.Count is not null}" ); } // cleanup of cache now we've used the tax value from it - _ragfairTaxService.ClearStoredOfferTaxById(offerRequest.Items.First()); + ragfairTaxService.ClearStoredOfferTaxById(offerRequest.Items.First()); var buyTradeRequest = CreateBuyTradeRequestObject(CurrencyType.RUB, tax.Value); - _paymentService.PayMoney(pmcData, buyTradeRequest, sessionId, output); + paymentService.PayMoney(pmcData, buyTradeRequest, sessionId, output); if (output.Warnings.Count > 0) { - _httpResponseUtil.AppendErrorToOutput( + httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText("ragfair-unable_to_pay_commission_fee", tax) + localisationService.GetText("ragfair-unable_to_pay_commission_fee", tax) ); return true; } @@ -1078,9 +1017,9 @@ public class RagfairController OnlyFunctional = item.OnlyFunctional, }); - return _ragfairOfferGenerator.CreateAndAddFleaOffer( + return ragfairOfferGenerator.CreateAndAddFleaOffer( sessionId, - _timeUtil.GetTimeStamp(), + timeUtil.GetTimeStamp(), formattedItems.ToList(), formattedRequirements.ToList(), loyalLevel, @@ -1107,9 +1046,9 @@ public class RagfairController return 0; } - return _paymentHelper.IsMoneyTpl(requirement.Template) - ? _handbookHelper.InRUB(requirement.Count.Value, requirement.Template) - : _itemHelper.GetDynamicItemPrice(requirement.Template).Value + return paymentHelper.IsMoneyTpl(requirement.Template) + ? handbookHelper.InRUB(requirement.Count.Value, requirement.Template) + : itemHelper.GetDynamicItemPrice(requirement.Template).Value * requirement.Count.Value; }); } @@ -1134,11 +1073,11 @@ public class RagfairController var rootItem = pmcData.Inventory?.Items?.FirstOrDefault(i => i.Id == itemId); if (rootItem is null) { - errorMessage = _serverLocalisationService.GetText( + errorMessage = localisationService.GetText( "ragfair-unable_to_find_item_in_inventory", new { id = itemId } ); - _logger.Error(errorMessage); + logger.Error(errorMessage); return new GetItemsToListOnFleaFromInventoryResult { @@ -1154,10 +1093,10 @@ public class RagfairController if (itemsToReturn?.Count == 0) { - errorMessage = _serverLocalisationService.GetText( + errorMessage = localisationService.GetText( "ragfair-unable_to_find_requested_items_in_inventory" ); - _logger.Error(errorMessage); + logger.Error(errorMessage); return new GetItemsToListOnFleaFromInventoryResult { ErrorMessage = errorMessage }; } @@ -1176,16 +1115,16 @@ public class RagfairController /// Id of offer to remove /// Session id of requesting player /// ItemEventRouterResponse - public ItemEventRouterResponse FlagOfferForRemoval(string offerId, string sessionId) + public ItemEventRouterResponse FlagOfferForRemoval(string offerId, MongoId sessionId) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); - var pmcData = _profileHelper.GetPmcProfile(sessionId); + var pmcData = profileHelper.GetPmcProfile(sessionId); var playerProfileOffers = pmcData?.RagfairInfo?.Offers; if (playerProfileOffers is null) { - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + localisationService.GetText( "ragfair-unable_to_remove_offer_not_found_in_profile", new { profileId = sessionId, offerId } ) @@ -1197,29 +1136,26 @@ public class RagfairController var playerOffer = playerProfileOffers?.FirstOrDefault(x => x.Id == offerId); if (playerOffer is null) { - _logger.Error( - _serverLocalisationService.GetText( - "ragfair-offer_not_found_in_profile", - new { offerId } - ) + logger.Error( + localisationService.GetText("ragfair-offer_not_found_in_profile", new { offerId }) ); - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText("ragfair-offer_not_found_in_profile_short") + localisationService.GetText("ragfair-offer_not_found_in_profile_short") ); } // Only reduce time to end if time remaining is greater than what we would set it to - var differenceInSeconds = playerOffer.EndTime - _timeUtil.GetTimeStamp(); + var differenceInSeconds = playerOffer.EndTime - timeUtil.GetTimeStamp(); if (differenceInSeconds > _ragfairConfig.Sell.ExpireSeconds) { // `expireSeconds` Default is 71 seconds - var newEndTime = _ragfairConfig.Sell.ExpireSeconds + _timeUtil.GetTimeStamp(); + var newEndTime = _ragfairConfig.Sell.ExpireSeconds + timeUtil.GetTimeStamp(); playerOffer.EndTime = (long?)Math.Round((double)newEndTime); } - _logger.Debug( + logger.Debug( $"Flagged player offer: {offerId} for expiry in: {TimeSpan.FromTicks(playerOffer.EndTime.Value).ToString()}" ); @@ -1234,27 +1170,27 @@ public class RagfairController /// ItemEventRouterResponse public ItemEventRouterResponse ExtendOffer( ExtendOfferRequestData extendRequest, - string sessionId + MongoId sessionId ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); - var pmcData = _profileHelper.GetPmcProfile(sessionId); + var pmcData = profileHelper.GetPmcProfile(sessionId); var playerOffers = pmcData.RagfairInfo.Offers; var playerOfferIndex = playerOffers.FindIndex(offer => offer.Id == extendRequest.OfferId); var secondsToAdd = extendRequest.RenewalTime * TimeUtil.OneHourAsSeconds; if (playerOfferIndex == -1) { - _logger.Warning( - _serverLocalisationService.GetText( + logger.Warning( + localisationService.GetText( "ragfair-offer_not_found_in_profile", new { offerId = extendRequest.OfferId } ) ); - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText("ragfair-offer_not_found_in_profile_short") + localisationService.GetText("ragfair-offer_not_found_in_profile_short") ); } @@ -1271,7 +1207,7 @@ public class RagfairController playerOffer.Items.Sum(offerItem => offerItem.Upd?.StackObjectsCount ?? 0); } - var tax = _ragfairTaxService.CalculateTax( + var tax = ragfairTaxService.CalculateTax( playerOffer.Items.First(), pmcData, playerOffer.RequirementsCost.Value, @@ -1280,12 +1216,12 @@ public class RagfairController ); var request = CreateBuyTradeRequestObject(CurrencyType.RUB, tax); - _paymentService.PayMoney(pmcData, request, sessionId, output); + paymentService.PayMoney(pmcData, request, sessionId, output); if (output.Warnings.Count > 0) { - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, - _serverLocalisationService.GetText("ragfair-unable_to_pay_commission_fee") + localisationService.GetText("ragfair-unable_to_pay_commission_fee") ); } } @@ -1328,17 +1264,17 @@ public class RagfairController /// Dictionary of tpl and item price public Dictionary GetAllFleaPrices() { - return _ragfairPriceService.GetAllFleaPrices(); + return ragfairPriceService.GetAllFleaPrices(); } public Dictionary GetStaticPrices() { - return _ragfairPriceService.GetAllStaticPrices(); + return ragfairPriceService.GetAllStaticPrices(); } public RagfairOffer? GetOfferByInternalId(string sessionId, GetRagfairOfferByIdRequest request) { - var offers = _ragfairOfferService.GetOffers(); + var offers = ragfairOfferService.GetOffers(); var offerToReturn = offers.FirstOrDefault(offer => offer.InternalId == request.Id); return offerToReturn; diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs index ecbf7bc1..70a8fc9c 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs @@ -9,7 +9,7 @@ using SPTarkov.Server.Core.Services; namespace SPTarkov.Server.Core.Controllers; [Injectable] -public class RepairController(EventOutputHolder _eventOutputHolder, RepairService _repairService) +public class RepairController(EventOutputHolder eventOutputHolder, RepairService repairService) { /// /// Handle TraderRepair event @@ -25,19 +25,19 @@ public class RepairController(EventOutputHolder _eventOutputHolder, RepairServic PmcData pmcData ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); // find the item to repair foreach (var repairItem in request.RepairItems) { - var repairDetails = _repairService.RepairItemByTrader( + var repairDetails = repairService.RepairItemByTrader( sessionID, pmcData, repairItem, request.TId ); - _repairService.PayForRepair( + repairService.PayForRepair( sessionID, pmcData, repairItem.Id, @@ -55,7 +55,7 @@ public class RepairController(EventOutputHolder _eventOutputHolder, RepairServic output.ProfileChanges[sessionID].Items.ChangedItems.Add(repairDetails.RepairedItem); // Add skill points for repairing weapons - _repairService.AddRepairSkillPoints(sessionID, repairDetails, pmcData); + repairService.AddRepairSkillPoints(sessionID, repairDetails, pmcData); } return output; @@ -75,10 +75,10 @@ public class RepairController(EventOutputHolder _eventOutputHolder, RepairServic PmcData pmcData ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); // repair item - var repairDetails = _repairService.RepairItemByKit( + var repairDetails = repairService.RepairItemByKit( sessionId, pmcData, body.RepairKitsInfo, @@ -86,13 +86,13 @@ public class RepairController(EventOutputHolder _eventOutputHolder, RepairServic output ); - _repairService.AddBuffToItem(repairDetails, pmcData); + repairService.AddBuffToItem(repairDetails, pmcData); // add repaired item to send to client output.ProfileChanges[sessionId].Items.ChangedItems.Add(repairDetails.RepairedItem); // Add skill points for repairing items - _repairService.AddRepairSkillPoints(sessionId, repairDetails, pmcData); + repairService.AddRepairSkillPoints(sessionId, repairDetails, pmcData); return output; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs index 95d8b04b..48bf4ca1 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs @@ -60,7 +60,7 @@ public class RepeatableQuestController( public ItemEventRouterResponse AcceptRepeatableQuest( PmcData pmcData, AcceptQuestRequestData acceptedQuest, - string sessionID + MongoId sessionID ) { // Create and store quest status object inside player profile @@ -114,7 +114,7 @@ public class RepeatableQuestController( public ItemEventRouterResponse ChangeRepeatableQuest( PmcData pmcData, RepeatableQuestChangeRequest changeRequest, - string sessionID + MongoId sessionID ) { var output = eventOutputHolder.GetOutput(sessionID); @@ -264,7 +264,7 @@ public class RepeatableQuestController( /// Players PMC profile /// Quest id to return /// RepeatableQuest - protected RepeatableQuest? GetRepeatableQuestFromProfile(PmcData pmcData, string questId) + protected RepeatableQuest? GetRepeatableQuestFromProfile(PmcData pmcData, MongoId questId) { foreach (var repeatableQuest in pmcData.RepeatableQuests) { @@ -366,7 +366,7 @@ public class RepeatableQuestController( /// Config for the quest type to generate /// protected RepeatableQuest? AttemptToGenerateRepeatableQuest( - string sessionId, + MongoId sessionId, PmcData pmcData, QuestTypePool questTypePool, RepeatableQuestConfig repeatableConfig @@ -420,7 +420,7 @@ public class RepeatableQuestController( /// Repeatable quest config /// RepeatableQuest public RepeatableQuest? PickAndGenerateRandomRepeatableQuest( - string sessionId, + MongoId sessionId, int pmcLevel, Dictionary pmcTraderInfo, QuestTypePool questTypePool, @@ -491,7 +491,7 @@ public class RepeatableQuestController( /// /// Profile to remove quest from /// Quest id to remove from profile - protected void RemoveQuestFromProfile(SptProfile fullProfile, string questToReplaceId) + protected void RemoveQuestFromProfile(SptProfile fullProfile, MongoId questToReplaceId) { // Find quest we're replacing in pmc profile quests array and remove it questHelper.FindAndRemoveQuestFromArrayIfExists( @@ -515,7 +515,7 @@ public class RepeatableQuestController( /// Id of quest to find /// Profile that contains quests to look through /// - protected GetRepeatableByIdResult? GetRepeatableById(string questId, PmcData pmcData) + protected GetRepeatableByIdResult? GetRepeatableById(MongoId questId, PmcData pmcData) { foreach (var repeatablesInProfile in pmcData.RepeatableQuests) { @@ -560,7 +560,7 @@ public class RepeatableQuestController( /// /// Session/Player id /// Array of repeatable quests - public List GetClientRepeatableQuests(string sessionID) + public List GetClientRepeatableQuests(MongoId sessionID) { var returnData = new List(); var fullProfile = profileHelper.GetFullProfile(sessionID); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs b/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs index d96b62d4..aadfb79a 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs @@ -20,24 +20,24 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class TradeController( - ISptLogger _logger, - DatabaseService _databaseService, - EventOutputHolder _eventOutputHolder, - TradeHelper _tradeHelper, - TimeUtil _timeUtil, - RandomUtil _randomUtil, - ItemHelper _itemHelper, - ProfileHelper _profileHelper, - RagfairOfferHelper _ragfairOfferHelper, - RagfairServer _ragfairServer, - HttpResponseUtil _httpResponseUtil, - ServerLocalisationService _serverLocalisationService, - MailSendService _mailSendService, - ConfigServer _configServer + ISptLogger logger, + DatabaseService databaseService, + EventOutputHolder eventOutputHolder, + TradeHelper tradeHelper, + TimeUtil timeUtil, + RandomUtil randomUtil, + ItemHelper itemHelper, + ProfileHelper profileHelper, + RagfairOfferHelper ragfairOfferHelper, + RagfairServer ragfairServer, + HttpResponseUtil httpResponseUtil, + ServerLocalisationService serverLocalisationService, + MailSendService mailSendService, + ConfigServer configServer ) { - protected readonly RagfairConfig _ragfairConfig = _configServer.GetConfig(); - protected readonly TraderConfig _traderConfig = _configServer.GetConfig(); + protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly TraderConfig _traderConfig = configServer.GetConfig(); /// /// Handle TradingConfirm event @@ -49,17 +49,17 @@ public class TradeController( public ItemEventRouterResponse ConfirmTrading( PmcData pmcData, ProcessBaseTradeRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); // Buying if (request.Type == "buy_from_trader") { var foundInRaid = _traderConfig.PurchasesAreFoundInRaid; var buyData = (ProcessBuyTradeRequestData)request; - _tradeHelper.BuyItem(pmcData, buyData, sessionID, foundInRaid, output); + tradeHelper.BuyItem(pmcData, buyData, sessionID, foundInRaid, output); return output; } @@ -68,15 +68,15 @@ public class TradeController( if (request.Type == "sell_to_trader") { var sellData = (ProcessSellTradeRequestData)request; - _tradeHelper.SellItem(pmcData, pmcData, sellData, sessionID, output); + tradeHelper.SellItem(pmcData, pmcData, sellData, sessionID, output); return output; } var errorMessage = $"Unhandled trade event: {request.Type}"; - _logger.Error(errorMessage); + logger.Error(errorMessage); - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, errorMessage, BackendErrorCodes.RagfairUnavailable @@ -93,17 +93,17 @@ public class TradeController( public ItemEventRouterResponse ConfirmRagfairTrading( PmcData pmcData, ProcessRagfairTradeRequestData request, - string sessionID + MongoId sessionID ) { - var output = _eventOutputHolder.GetOutput(sessionID); + var output = eventOutputHolder.GetOutput(sessionID); foreach (var offer in request.Offers) { - var fleaOffer = _ragfairServer.GetOffer(offer.Id); + var fleaOffer = ragfairServer.GetOffer(offer.Id); if (fleaOffer is null) { - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, $"Offer with ID {offer.Id} not found", BackendErrorCodes.OfferNotFound @@ -112,18 +112,18 @@ public class TradeController( if (offer.Count == 0) { - var errorMessage = _serverLocalisationService.GetText( + var errorMessage = serverLocalisationService.GetText( "ragfair-unable_to_purchase_0_count_item", - _itemHelper.GetItem(fleaOffer.Items[0].Template).Value.Name + itemHelper.GetItem(fleaOffer.Items[0].Template).Value.Name ); - return _httpResponseUtil.AppendErrorToOutput( + return httpResponseUtil.AppendErrorToOutput( output, errorMessage, BackendErrorCodes.OfferOutOfStock ); } - if (_ragfairOfferHelper.OfferIsFromTrader(fleaOffer)) + if (ragfairOfferHelper.OfferIsFromTrader(fleaOffer)) { BuyTraderItemFromRagfair(sessionID, pmcData, fleaOffer, offer, output); } @@ -151,7 +151,7 @@ public class TradeController( /// request data from client /// Output to send back to client protected void BuyTraderItemFromRagfair( - string sessionId, + MongoId sessionId, PmcData pmcData, RagfairOffer fleaOffer, OfferRequest requestOffer, @@ -163,12 +163,12 @@ public class TradeController( { var errorMessage = $"Unable to buy item: {fleaOffer.Items[0].Template} from trader: {fleaOffer.User.Id} as loyalty level too low, skipping"; - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug(errorMessage); + logger.Debug(errorMessage); } - _httpResponseUtil.AppendErrorToOutput( + httpResponseUtil.AppendErrorToOutput( output, errorMessage, BackendErrorCodes.RagfairUnavailable @@ -188,7 +188,7 @@ public class TradeController( SchemeId = 0, SchemeItems = requestOffer.Items, }; - _tradeHelper.BuyItem( + tradeHelper.BuyItem( pmcData, buyData, sessionId, @@ -197,7 +197,7 @@ public class TradeController( ); // Remove/lower offer quantity of item purchased from trader flea offer - _ragfairServer.ReduceOfferQuantity(fleaOffer.Id, requestOffer.Count ?? 0); + ragfairServer.ReduceOfferQuantity(fleaOffer.Id, requestOffer.Count ?? 0); } /// @@ -209,7 +209,7 @@ public class TradeController( /// request data from client /// Output to send back to client protected void BuyPmcItemFromRagfair( - string sessionId, + MongoId sessionId, PmcData pmcData, RagfairOffer fleaOffer, OfferRequest requestOffer, @@ -228,7 +228,7 @@ public class TradeController( }; // buyItem() must occur prior to removing the offer stack, otherwise item inside offer doesn't exist for confirmTrading() to use - _tradeHelper.BuyItem( + tradeHelper.BuyItem( pmcData, buyData, sessionId, @@ -247,13 +247,13 @@ public class TradeController( if (IsPlayerOffer(fleaOffer.Id, fleaOffer.User?.Id)) { // Complete selling the offer now it has been purchased - _ragfairOfferHelper.CompleteOffer(offerOwnerId, fleaOffer, offerBuyCount ?? 0); + ragfairOfferHelper.CompleteOffer(offerOwnerId, fleaOffer, offerBuyCount ?? 0); return; } // Remove/lower offer quantity of item purchased from PMC flea offer - _ragfairServer.ReduceOfferQuantity(fleaOffer.Id, requestOffer.Count ?? 0); + ragfairServer.ReduceOfferQuantity(fleaOffer.Id, requestOffer.Count ?? 0); } /// @@ -262,7 +262,7 @@ public class TradeController( /// id of the offer /// Owner id /// true if offer was made by a player - protected bool IsPlayerOffer(string offerId, string? offerOwnerId) + protected bool IsPlayerOffer(string offerId, MongoId? offerOwnerId) { // No ownerId, not player offer if (offerOwnerId is null) @@ -270,7 +270,7 @@ public class TradeController( return false; } - var offerCreatorProfile = _profileHelper.GetPmcProfile(offerOwnerId); + var offerCreatorProfile = profileHelper.GetPmcProfile(offerOwnerId.Value); if (offerCreatorProfile is null || offerCreatorProfile.RagfairInfo.Offers?.Count == 0) // No profile or no offers { @@ -302,10 +302,10 @@ public class TradeController( public ItemEventRouterResponse SellScavItemsToFence( PmcData pmcData, SellScavItemsToFenceRequestData request, - string sessionId + MongoId sessionId ) { - var output = _eventOutputHolder.GetOutput(sessionId); + var output = eventOutputHolder.GetOutput(sessionId); MailMoneyToPlayer(sessionId, (int)request.TotalValue, Traders.FENCE); @@ -318,11 +318,11 @@ public class TradeController( /// Session id /// amount of roubles to send /// Trader to sell items to - protected void MailMoneyToPlayer(string sessionId, int roublesToSend, string trader) + protected void MailMoneyToPlayer(MongoId sessionId, int roublesToSend, MongoId trader) { - if (_logger.IsLogEnabled(LogLevel.Debug)) + if (logger.IsLogEnabled(LogLevel.Debug)) { - _logger.Debug($"Selling scav items to fence for {roublesToSend} roubles"); + logger.Debug($"Selling scav items to fence for {roublesToSend} roubles"); } // Create single currency item with all currency on it @@ -334,20 +334,20 @@ public class TradeController( }; // Ensure money is properly split to follow its max stack size limit - var curencyReward = _itemHelper.SplitStackIntoSeparateItems(rootCurrencyReward); + var curencyReward = itemHelper.SplitStackIntoSeparateItems(rootCurrencyReward); // Send mail from trader - _mailSendService.SendLocalisedNpcMessageToPlayer( + mailSendService.SendLocalisedNpcMessageToPlayer( sessionId, trader, MessageType.MessageWithItems, - _randomUtil.GetArrayValue( - _databaseService.GetTrader(trader).Dialogue.TryGetValue("soldItems", out var items) + randomUtil.GetArrayValue( + databaseService.GetTrader(trader).Dialogue.TryGetValue("soldItems", out var items) ? items : new List() ), curencyReward.SelectMany(x => x).ToList(), - _timeUtil.GetHoursAsSeconds(72) + timeUtil.GetHoursAsSeconds(72) ); } @@ -360,9 +360,9 @@ public class TradeController( /// Trader being sold to, to perform buy category check against /// Rouble price protected int GetPriceOfItemAndChildren( - string parentItemId, + MongoId parentItemId, List items, - Dictionary handbookPrices, + Dictionary handbookPrices, TraderBase traderDetails ) { @@ -371,11 +371,11 @@ public class TradeController( var totalPrice = 0; foreach (var itemToSell in itemWithChildren) { - var itemDetails = _itemHelper.GetItem(itemToSell.Template); + var itemDetails = itemHelper.GetItem(itemToSell.Template); if ( !( itemDetails.Key - && _itemHelper.IsOfBaseclasses( + && itemHelper.IsOfBaseclasses( itemDetails.Value.Id, traderDetails.ItemsBuy.Category ) diff --git a/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs b/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs index 50164598..cbf2d891 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs @@ -2,6 +2,7 @@ using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Extensions; using SPTarkov.Server.Core.Generators; using SPTarkov.Server.Core.Helpers; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Game; using SPTarkov.Server.Core.Models.Enums; @@ -138,7 +139,7 @@ public class TraderController( /// /// session id /// Return a list of all traders - public List GetAllTraders(string sessionId) + public List GetAllTraders(MongoId sessionId) { var traders = new List(); var pmcData = profileHelper.GetPmcProfile(sessionId); @@ -179,7 +180,7 @@ public class TraderController( /// Session/Player id /// /// - public TraderBase? GetTrader(string sessionId, string traderId) + public TraderBase? GetTrader(MongoId sessionId, MongoId traderId) { return traderHelper.GetTrader(sessionId, traderId); } @@ -190,7 +191,7 @@ public class TraderController( /// Session/Player id /// /// - public TraderAssort GetAssort(string sessionId, string traderId) + public TraderAssort GetAssort(MongoId sessionId, MongoId traderId) { return traderAssortHelper.GetAssort(sessionId, traderId); } @@ -199,7 +200,7 @@ public class TraderController( /// Handle client/items/prices/TRADERID /// /// - public GetItemPricesResponse GetItemPrices(string sessionId, string traderId) + public GetItemPricesResponse GetItemPrices(MongoId sessionId, MongoId traderId) { var handbookPrices = ragfairPriceService.GetAllStaticPrices(); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs b/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs index e96a4759..dddeb9ed 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/WeatherController.cs @@ -13,14 +13,14 @@ namespace SPTarkov.Server.Core.Controllers; [Injectable] public class WeatherController( - ISptLogger _logger, - WeatherGenerator _weatherGenerator, - SeasonalEventService _seasonalEventService, - RaidWeatherService _raidWeatherService, - ConfigServer _configServer + ISptLogger logger, + WeatherGenerator weatherGenerator, + SeasonalEventService seasonalEventService, + RaidWeatherService raidWeatherService, + ConfigServer configServer ) { - protected WeatherConfig _weatherConfig = _configServer.GetConfig(); + protected WeatherConfig _weatherConfig = configServer.GetConfig(); /// /// Handle client/weather @@ -37,8 +37,8 @@ public class WeatherController( Season = Season.AUTUMN, }; - _weatherGenerator.CalculateGameTime(result); - result.Weather = _weatherGenerator.GenerateWeather(result.Season.Value); + weatherGenerator.CalculateGameTime(result); + result.Weather = weatherGenerator.GenerateWeather(result.Season.Value); return result; } @@ -52,11 +52,11 @@ public class WeatherController( { var result = new GetLocalWeatherResponseData { - Season = _seasonalEventService.GetActiveWeatherSeason(), + Season = seasonalEventService.GetActiveWeatherSeason(), Weather = [], }; - result.Weather.AddRange(_raidWeatherService.GetUpcomingWeather()); + result.Weather.AddRange(raidWeatherService.GetUpcomingWeather()); return result; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/WishlistController.cs b/Libraries/SPTarkov.Server.Core/Controllers/WishlistController.cs index dacdc16c..6de1540d 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/WishlistController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/WishlistController.cs @@ -9,7 +9,7 @@ using SPTarkov.Server.Core.Utils.Json; namespace SPTarkov.Server.Core.Controllers; [Injectable] -public class WishlistController(EventOutputHolder _eventOutputHolder) +public class WishlistController(EventOutputHolder eventOutputHolder) { /// /// Handle AddToWishList @@ -30,7 +30,7 @@ public class WishlistController(EventOutputHolder _eventOutputHolder) pmcData.WishList.Dictionary.Add(item.Key, item.Value); } - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -43,7 +43,7 @@ public class WishlistController(EventOutputHolder _eventOutputHolder) public ItemEventRouterResponse RemoveFromWishList( PmcData pmcData, RemoveFromWishlistRequest request, - string sessionId + MongoId sessionId ) { foreach (var itemId in request.Items) @@ -51,7 +51,7 @@ public class WishlistController(EventOutputHolder _eventOutputHolder) pmcData.WishList.Dictionary.Remove(itemId); } - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } /// @@ -64,11 +64,11 @@ public class WishlistController(EventOutputHolder _eventOutputHolder) public ItemEventRouterResponse ChangeWishListItemCategory( PmcData pmcData, ChangeWishlistItemCategoryRequest request, - string sessionId + MongoId sessionId ) { pmcData.WishList.Dictionary[request.Item] = request.Category.Value; - return _eventOutputHolder.GetOutput(sessionId); + return eventOutputHolder.GetOutput(sessionId); } } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/BotBase.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/BotBase.cs index c5eec3fc..ff9796ef 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/BotBase.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/BotBase.cs @@ -145,7 +145,7 @@ public record TaskConditionCounter public Dictionary? ExtensionData { get; set; } [JsonPropertyName("id")] - public string? Id { get; set; } + public MongoId? Id { get; set; } [JsonPropertyName("type")] public string? Type { get; set; } @@ -157,7 +157,7 @@ public record TaskConditionCounter /// Quest id /// [JsonPropertyName("sourceId")] - public string? SourceId { get; set; } + public MongoId? SourceId { get; set; } } public record UnlockedInfo diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Notifier/Notifier.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Notifier/Notifier.cs index 10a06cd0..93ec3300 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Notifier/Notifier.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Notifier/Notifier.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Notifier; @@ -11,7 +12,7 @@ public record NotifierChannel public string? Server { get; set; } [JsonPropertyName("channel_id")] - public string? ChannelId { get; set; } + public MongoId? ChannelId { get; set; } [JsonPropertyName("url")] public string? Url { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SptProfile.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SptProfile.cs index ecfd3061..46bf7fe4 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SptProfile.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SptProfile.cs @@ -90,7 +90,7 @@ public record Info public MongoId? ProfileId { get; set; } [JsonPropertyName("scavId")] - public string? ScavengerId { get; set; } + public MongoId? ScavengerId { get; set; } [JsonPropertyName("aid")] public int? Aid { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs b/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs index a1cbc4ee..2f014fad 100644 --- a/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs @@ -746,7 +746,7 @@ public class LocationLifecycleService( // insert scav quest counters into pmc profile foreach (var counter in matchingCounters) { - pmcProfile.TaskConditionCounters[counter.Value.Id] = counter.Value; + pmcProfile.TaskConditionCounters[counter.Value.Id.Value] = counter.Value; } // Find Matching PMC Quest