diff --git a/Benchmarks/MathUtilInterpBenchmarks.cs b/Benchmarks/MathUtilInterpBenchmarks.cs index 9c25c43b..7945d059 100644 --- a/Benchmarks/MathUtilInterpBenchmarks.cs +++ b/Benchmarks/MathUtilInterpBenchmarks.cs @@ -1,5 +1,4 @@ -using System; -using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Attributes; using SPTarkov.Server.Core.Utils; namespace Benchmarks @@ -11,8 +10,8 @@ namespace Benchmarks private MathUtil _mathUtil; private double input = 15d; - private new List x = [1, 10, 20, 30, 40, 50, 60]; - private new List y = [11000, 20000, 32000, 45000, 58000, 70000, 82000]; + private List x = [1, 10, 20, 30, 40, 50, 60]; + private List y = [11000, 20000, 32000, 45000, 58000, 70000, 82000]; [GlobalSetup] public void Setup() diff --git a/Libraries/SPTarkov.DI/SingletonStateHolder.cs b/Libraries/SPTarkov.DI/SingletonStateHolder.cs index c3c651a9..2b00e3ab 100644 --- a/Libraries/SPTarkov.DI/SingletonStateHolder.cs +++ b/Libraries/SPTarkov.DI/SingletonStateHolder.cs @@ -1,11 +1,6 @@ namespace SPTarkov.DI; -public class SingletonStateHolder +public class SingletonStateHolder(T state) { - public T State { get; } - - public SingletonStateHolder(T state) - { - State = state; - } + public T State { get; } = state; } diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/DialogueCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/DialogueCallbacks.cs index 19c45693..0271ea39 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/DialogueCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/DialogueCallbacks.cs @@ -91,7 +91,7 @@ public class DialogueCallbacks( /// Handle client/mail/dialog/view /// /// - /// + /// /// Session/player id /// public virtual ValueTask GetMailDialogView( diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/MatchCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/MatchCallbacks.cs index f0a43a53..59223d5f 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/MatchCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/MatchCallbacks.cs @@ -32,7 +32,7 @@ public class MatchCallbacks( /// Handle client/match/exit /// /// - /// + /// /// Session/player id /// public ValueTask ExitMatch(string url, EmptyRequestData _, MongoId sessionID) @@ -320,7 +320,7 @@ public class MatchCallbacks( /// Handle client/match/group/raid/not-ready /// /// - /// + /// /// Session/player id /// public ValueTask NotRaidReady(string url, EmptyRequestData _, MongoId sessionID) diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/PrestigeCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/PrestigeCallbacks.cs index 99536e54..1449c1ee 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/PrestigeCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/PrestigeCallbacks.cs @@ -17,7 +17,7 @@ public class PrestigeCallbacks( /// Handle client/prestige/list /// /// - /// + /// /// Session/player id /// public ValueTask GetPrestige(string url, EmptyRequestData _, MongoId sessionID) diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/QuestCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/QuestCallbacks.cs index 7b830828..3d0aec0a 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/QuestCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/QuestCallbacks.cs @@ -102,7 +102,7 @@ public class QuestCallbacks( /// Handle client/repeatalbeQuests/activityPeriods /// /// - /// + /// /// Session/player id /// public ValueTask ActivityPeriods(string url, EmptyRequestData _, MongoId sessionID) diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs index ca1121fe..9c8641ea 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/RagfairCallbacks.cs @@ -138,7 +138,7 @@ public class RagfairCallbacks( /// Called when clicking an item to list on flea /// /// - /// + /// /// Session/player id /// public ValueTask GetFleaPrices(string url, EmptyRequestData _, MongoId sessionID) diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs index d0421012..fed8f376 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/TraderCallbacks.cs @@ -68,7 +68,7 @@ public class TraderCallbacks( /// Handle /singleplayer/moddedTraders /// /// - /// + /// /// Session/player id /// public ValueTask GetModdedTraderData(string url, EmptyRequestData _, MongoId sessionID) diff --git a/Libraries/SPTarkov.Server.Core/Callbacks/WeatherCallbacks.cs b/Libraries/SPTarkov.Server.Core/Callbacks/WeatherCallbacks.cs index 04db12d9..7711b73f 100644 --- a/Libraries/SPTarkov.Server.Core/Callbacks/WeatherCallbacks.cs +++ b/Libraries/SPTarkov.Server.Core/Callbacks/WeatherCallbacks.cs @@ -16,7 +16,7 @@ public class WeatherCallbacks( /// Handle client/weather /// /// - /// + /// /// Session/player id /// public ValueTask GetWeather(string url, EmptyRequestData _, MongoId sessionID) @@ -28,7 +28,7 @@ public class WeatherCallbacks( /// Handle client/localGame/weather /// /// - /// + /// /// Session/player id /// public ValueTask GetLocalWeather(string url, EmptyRequestData _, MongoId sessionID) diff --git a/Libraries/SPTarkov.Server.Core/Controllers/BotController.cs b/Libraries/SPTarkov.Server.Core/Controllers/BotController.cs index 39aa2081..14c14a4d 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/BotController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/BotController.cs @@ -78,7 +78,6 @@ public class BotController( /// Which user is requesting his bot settings /// what bot the server is requesting settings for /// difficulty level server requested settings for - /// OPTIONAL - applicationContext Data stored at start of raid /// OPTIONAL - should raid settings chosen pre-raid be ignored /// Difficulty object public DifficultyCategories GetBotDifficulty( @@ -92,7 +91,7 @@ public class BotController( var raidConfig = _profileActivityService .GetProfileActivityRaidData(sessionId) - ?.RaidConfiguration; + .RaidConfiguration; if (!(raidConfig != null || ignoreRaidSettings)) { diff --git a/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs b/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs index 1409fd26..0f3e6525 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/BuildController.cs @@ -33,7 +33,7 @@ public class BuildController( const string secureContainerSlotId = "SecuredContainer"; var profile = profileHelper.GetFullProfile(sessionID); - if (profile?.UserBuildData is null) + if (profile.UserBuildData is null) { profile.UserBuildData = new UserBuilds { @@ -50,12 +50,12 @@ public class BuildController( // Get players secure container var playerSecureContainer = - profile?.CharacterData?.PmcData?.Inventory?.Items?.FirstOrDefault(x => + profile.CharacterData?.PmcData?.Inventory?.Items?.FirstOrDefault(x => x.SlotId == secureContainerSlotId ); var firstDefaultItemsSecureContainer = defaultEquipmentPresetsClone - ?.FirstOrDefault() + .FirstOrDefault() ?.Items?.FirstOrDefault(x => x.SlotId == secureContainerSlotId); if ( @@ -81,7 +81,7 @@ public class BuildController( var userBuildsClone = cloner.Clone(profile?.UserBuildData); userBuildsClone.EquipmentBuilds ??= []; - userBuildsClone?.EquipmentBuilds?.AddRange(defaultEquipmentPresetsClone); + userBuildsClone.EquipmentBuilds?.AddRange(defaultEquipmentPresetsClone); return userBuildsClone; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs b/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs index d55f39c7..c2e16b6c 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/CustomizationController.cs @@ -34,17 +34,17 @@ public class CustomizationController( /// trader to look up clothing for /// Session id /// Suit array - public List GetTraderSuits(string traderId, MongoId sessionId) + public List GetTraderSuits(MongoId traderId, MongoId sessionId) { 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(); + var matchingSuits = suits?.Where(s => clothing.ContainsKey(s.SuiteId)).ToList(); matchingSuits = matchingSuits ?.Where(s => - clothing[s.SuiteId ?? string.Empty] - ?.Properties?.Side?.Contains(pmcData?.Info?.Side ?? string.Empty) ?? false + clothing[s.SuiteId]?.Properties?.Side?.Contains(pmcData?.Info?.Side ?? string.Empty) + ?? false ) .ToList(); @@ -90,9 +90,9 @@ public class CustomizationController( } var suitId = traderOffer.SuiteId; - if (OutfitAlreadyPurchased(suitId ?? string.Empty, sessionId)) + if (OutfitAlreadyPurchased(traderOffer.SuiteId, sessionId)) { - var suitDetails = databaseService.GetCustomization()!.GetValueOrDefault(suitId); + var suitDetails = databaseService.GetCustomization().GetValueOrDefault(suitId); logger.Error( serverLocalisationService.GetText( "customisation-item_already_purchased", @@ -127,7 +127,7 @@ public class CustomizationController( /// clothing id /// Session id of profile to check for clothing in /// true if already purchased - protected bool OutfitAlreadyPurchased(object suitId, MongoId sessionId) + protected bool OutfitAlreadyPurchased(MongoId suitId, MongoId sessionId) { var fullProfile = profileHelper.GetFullProfile(sessionId); @@ -297,9 +297,7 @@ public class CustomizationController( /// Profile to update protected void ApplyClothingItemToProfile(CustomizationSetOption customisation, PmcData pmcData) { - var dbSuit = databaseService.GetCustomization()[customisation.Id!]; - - if (dbSuit is null) + if (!databaseService.GetCustomization().TryGetValue(customisation.Id, out var dbSuit)) { logger.Error( $"Unable to find suit customisation id: {customisation.Id}, cannot apply clothing to player profile: {pmcData.Id}" diff --git a/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs b/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs index e70f3830..04ff5891 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/DialogueController.cs @@ -172,7 +172,7 @@ public class DialogueController( var result = new DialogueInfo { Id = dialogue.Id, - Type = dialogue?.Type ?? MessageType.NpcTraderMessage, + Type = dialogue.Type ?? MessageType.NpcTraderMessage, Message = dialogueHelper.GetMessagePreview(dialogue), New = dialogue?.New, AttachmentsNew = dialogue?.AttachmentsNew, @@ -210,7 +210,7 @@ public class DialogueController( dialog.Users.Add( new UserDialogInfo { - Id = profile.CharacterData?.PmcData?.SessionId, + Id = profile.CharacterData.PmcData.SessionId.Value, Aid = profile.CharacterData?.PmcData?.Aid, Info = new UserDialogDetails { @@ -478,7 +478,7 @@ public class DialogueController( public virtual void SetRead(List? dialogueIds, MongoId sessionId) { var dialogs = dialogueHelper.GetDialogsForProfile(sessionId); - if (dialogs?.Any() != true) + if (dialogs.Any() != true) { logger.Error( serverLocalisationService.GetText( @@ -543,7 +543,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 @@ -638,9 +638,9 @@ public class DialogueController( // Only add the profile to the friends list if it doesn't already exist var profile = saveServer.GetProfile(sessionID); - if (!profile.FriendProfileIds.Contains(request.To)) + if (!profile.FriendProfileIds.Contains(request.To.Value)) { - profile.FriendProfileIds.Add(request.To); + profile.FriendProfileIds.Add(request.To.Value); } // We need to delay this so that the friend request gets properly added to the clientside list before we accept it diff --git a/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs b/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs index 9379eafc..aa8d6f47 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/GameController.cs @@ -440,13 +440,13 @@ public class GameController( // One day post-profile creation if (currentTimeStamp > timeStampProfileCreated + oneDaySeconds) { - giftService.SendPraporStartingGift(pmcProfile.SessionId!, 1); + giftService.SendPraporStartingGift(pmcProfile.SessionId.Value, 1); } // Two day post-profile creation if (currentTimeStamp > timeStampProfileCreated + oneDaySeconds * 2) { - giftService.SendPraporStartingGift(pmcProfile.SessionId!, 2); + giftService.SendPraporStartingGift(pmcProfile.SessionId.Value, 2); } } @@ -456,7 +456,11 @@ public class GameController( /// protected void SendMechanicGiftsToNewProfile(PmcData pmcProfile) { - giftService.SendGiftWithSilentReceivedCheck("MechanicGiftDay1", pmcProfile.SessionId, 1); + giftService.SendGiftWithSilentReceivedCheck( + "MechanicGiftDay1", + pmcProfile.SessionId.Value, + 1 + ); } /// diff --git a/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs b/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs index 133c770c..920145d6 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/HealthController.cs @@ -304,13 +304,15 @@ public class HealthController( return output; } - foreach (var bodyPartKvP in healthTreatmentRequest.Difference.BodyParts.GetAllPropsAsDict()) + foreach ( + var (key, rawEffects) in healthTreatmentRequest.Difference.BodyParts.GetAllPropsAsDict() + ) { // Get body part from request + from pmc profile - var partRequest = (BodyPartEffects)bodyPartKvP.Value; - var profilePart = pmcData.Health.BodyParts[bodyPartKvP.Key]; + var partRequest = (BodyPartEffects)rawEffects; + var profilePart = pmcData.Health.BodyParts[key]; - // Bodypart healing is chosen when part request hp is above 0 + // Body part healing is chosen when part request hp is above 0 if (partRequest.Health > 0) // Heal bodypart { @@ -318,18 +320,18 @@ public class HealthController( } // Check for effects to remove - if (partRequest.Effects?.Count > 0) + if (partRequest.Effects.Count > 0) { // Found some, loop over them and remove from pmc profile foreach (var effect in partRequest.Effects) { - pmcData.Health.BodyParts[bodyPartKvP.Key].Effects.Remove(effect); + pmcData.Health.BodyParts[key].Effects.Remove(effect); } // Remove empty effect object - if (pmcData.Health.BodyParts[bodyPartKvP.Key].Effects.Count == 0) + if (pmcData.Health.BodyParts[key].Effects.Count == 0) { - pmcData.Health.BodyParts[bodyPartKvP.Key].Effects = null; + pmcData.Health.BodyParts[key].Effects = null; } } } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs b/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs index 3c8c7059..57d4cfe4 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/HideoutController.cs @@ -212,7 +212,19 @@ public class HideoutController( } // Apply bonuses - var hideoutStage = hideoutData.Stages[profileHideoutArea.Level.ToString()]; + if ( + !hideoutData.Stages.TryGetValue( + profileHideoutArea.Level.ToString(), + out var hideoutStage + ) + ) + { + logger.Error( + $"Stage level: {profileHideoutArea.Level} not found for area: {request.AreaType}" + ); + + return; + } var bonuses = hideoutStage.Bonuses; if (bonuses?.Count > 0) { @@ -223,7 +235,7 @@ public class HideoutController( } // Upgrade includes a container improvement/addition - if (!string.IsNullOrEmpty(hideoutStage?.Container)) + if (!string.IsNullOrEmpty(hideoutStage.Container)) { AddContainerImprovementToProfile( output, @@ -411,7 +423,7 @@ public class HideoutController( if (existingInventoryItem is not null) { // Update existing items container tpl to point to new id (tpl) - existingInventoryItem.Template = hideoutStage.Container; + existingInventoryItem.Template = hideoutStage.Container.Value; return; } @@ -420,7 +432,7 @@ public class HideoutController( var newContainerItem = new Item { Id = dbHideoutArea.Id, - Template = hideoutStage.Container, + Template = hideoutStage.Container.Value, }; pmcData.Inventory.Items.Add(newContainerItem); } @@ -611,7 +623,7 @@ public class HideoutController( BotHideoutArea hideoutArea ) { - var slotIndexToRemove = removeResourceRequest?.Slots?.FirstOrDefault(); + var slotIndexToRemove = removeResourceRequest.Slots?.FirstOrDefault(); if (slotIndexToRemove is null) { logger.Error( @@ -1709,7 +1721,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).Value.Properties.Slots; foreach (var mannequinSlot in slots) { // Check if we've already added this mannequin diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs index a21ecbf7..bf6a8bf9 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InsuranceController.cs @@ -559,7 +559,7 @@ public class InsuranceController( var price = ragfairPriceService.GetDynamicItemPrice(attachment.Template, Money.ROUBLES); if (price is not null) { - result[attachment.Id] = Math.Round(price ?? 0); + result.Add(attachment.Id, Math.Round(price.Value)); } } @@ -675,7 +675,7 @@ public class InsuranceController( /// Edge case - labyrinth doesn't allow for insurance returns unless location config is edited /// /// The insured items to process - /// OPTIONAL - id of labs location + /// OPTIONAL - id of labyrinth location /// protected bool IsMapLabyrinthAndInsuranceDisabled( Insurance insurance, diff --git a/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs b/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs index 69714973..9c5dff19 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/InventoryController.cs @@ -59,7 +59,7 @@ public class InventoryController( // Changes made to result apply to character inventory var ownerInventoryItems = inventoryHelper.GetOwnerInventoryItems( moveRequest, - moveRequest.Item, + moveRequest.Item.Value, sessionId ); if (ownerInventoryItems.SameInventory.GetValueOrDefault(false)) @@ -503,14 +503,7 @@ public class InventoryController( inventoryItem.ParentId = change.ParentId; inventoryItem.SlotId = change.SlotId; - if (change.Location is not null) - { - inventoryItem.Location = change.Location; - } - else - { - inventoryItem.Location = null; - } + inventoryItem.Location = change.Location ?? null; } } @@ -829,9 +822,7 @@ public class InventoryController( playerData = profileHelper.GetScavProfile(sessionId); } - var itemToFold = playerData.Inventory.Items.FirstOrDefault(item => - item?.Id == request.Item - ); + var itemToFold = playerData.Inventory.Items.FirstOrDefault(item => item.Id == request.Item); if (itemToFold is null) { // Item not found @@ -897,32 +888,18 @@ public class InventoryController( ); } - // to.id is the parentid + // to.id is the parentId itemOne.ParentId = request.To.Id; - // to.container is the slotid + // to.container is the slotId itemOne.SlotId = request.To.Container; // Request object has location data, add it in, otherwise remove existing location from object - if (request.To.Location is not null) - { - itemOne.Location = request.To.Location; - } - else - { - itemOne.Location = null; - } + itemOne.Location = request.To.Location ?? null; itemTwo.ParentId = request.To2.Id; itemTwo.SlotId = request.To2.Container; - if (request.To2.Location is not null) - { - itemTwo.Location = request.To2.Location; - } - else - { - itemTwo.Location = null; - } + itemTwo.Location = request.To2.Location ?? null; // Client already informed of inventory locations, nothing for us to do return eventOutputHolder.GetOutput(sessionId); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs b/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs index 9822dcc4..0c604e7e 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/LauncherController.cs @@ -224,7 +224,7 @@ public class LauncherController( /// /// Get the mods a profile has ever loaded into game with /// - /// Session/Player id + /// Session/Player id /// Array of mod details public List GetServerModsProfileUsed(MongoId sessionId) { diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs index 05835aba..ae267262 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RagfairController.cs @@ -48,7 +48,7 @@ public class RagfairController( ConfigServer configServer ) { - protected RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); /// /// Check all profiles and sell player offers / send player money for listing if it sold @@ -127,11 +127,7 @@ 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) - ) - ) + foreach (var traderOffer in result.Offers.Where(ragfairOfferHelper.OfferIsFromTrader)) { // For the items, check the barter schemes. The method getDisplayableAssorts sets a flag sptQuestLocked // to true if the quest is not completed yet @@ -353,7 +349,7 @@ public class RagfairController( ); } - if (searchRequest.NeededSearchId?.Length > 0) + if (searchRequest.NeededSearchId is not null) { return ragfairOfferHelper.GetOffersThatRequireItem(searchRequest, pmcProfile); } @@ -521,7 +517,7 @@ public class RagfairController( /// Is offer valid protected bool IsValidPlayerOfferRequest(AddOfferRequestData offerRequest) { - if (offerRequest?.Items is null || offerRequest.Items.Count == 0) + if (offerRequest.Items is null || offerRequest.Items.Count == 0) { logger.Error(localisationService.GetText("ragfair-invalid_player_offer_request")); @@ -1091,7 +1087,7 @@ public class RagfairController( itemsToReturn.Add(pmcData.Inventory.Items.FindAndReturnChildrenAsItems(itemId)); } - if (itemsToReturn?.Count == 0) + if (itemsToReturn.Count == 0) { errorMessage = localisationService.GetText( "ragfair-unable_to_find_requested_items_in_inventory" @@ -1280,7 +1276,7 @@ public class RagfairController( return offerToReturn; } - public record GetItemsToListOnFleaFromInventoryResult + protected record GetItemsToListOnFleaFromInventoryResult { public List>? Items { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs index 70a8fc9c..bfb0d764 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RepairController.cs @@ -34,7 +34,7 @@ public class RepairController(EventOutputHolder eventOutputHolder, RepairService sessionID, pmcData, repairItem, - request.TId + request.TraderId ); repairService.PayForRepair( @@ -42,7 +42,7 @@ public class RepairController(EventOutputHolder eventOutputHolder, RepairService pmcData, repairItem.Id, repairDetails.RepairCost.Value, - request.TId, + request.TraderId, output ); diff --git a/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs b/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs index d4ac3353..6557bed0 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/RepeatableQuestController.cs @@ -805,7 +805,7 @@ public class RepeatableQuestController( protected bool PlayerHasDailyScavQuestsUnlocked(PmcData pmcData) { return pmcData - ?.Hideout?.Areas?.FirstOrDefault(hideoutArea => + .Hideout?.Areas?.FirstOrDefault(hideoutArea => hideoutArea.Type == HideoutAreas.IntelligenceCenter ) ?.Level >= 1; diff --git a/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs b/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs index aadfb79a..37857228 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/TradeController.cs @@ -334,7 +334,7 @@ public class TradeController( }; // Ensure money is properly split to follow its max stack size limit - var curencyReward = itemHelper.SplitStackIntoSeparateItems(rootCurrencyReward); + var currencyReward = itemHelper.SplitStackIntoSeparateItems(rootCurrencyReward); // Send mail from trader mailSendService.SendLocalisedNpcMessageToPlayer( @@ -344,9 +344,9 @@ public class TradeController( randomUtil.GetArrayValue( databaseService.GetTrader(trader).Dialogue.TryGetValue("soldItems", out var items) ? items - : new List() + : [] ), - curencyReward.SelectMany(x => x).ToList(), + currencyReward.SelectMany(x => x).ToList(), timeUtil.GetHoursAsSeconds(72) ); } diff --git a/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs b/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs index cbf2d891..e1011337 100644 --- a/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs +++ b/Libraries/SPTarkov.Server.Core/Controllers/TraderController.cs @@ -58,7 +58,7 @@ public class TraderController( } // Adjust price by traderPriceMultiplier config property - if (!TraderConfig.TraderPriceMultiplier.Approx(1, 0.001)) + if (!TraderConfig.TraderPriceMultiplier.Approx(1)) { AdjustTraderItemPrices(trader, TraderConfig.TraderPriceMultiplier); } @@ -82,7 +82,7 @@ public class TraderController( { foreach (var kvp in trader.Assort?.BarterScheme) { - var barterSchemeItem = kvp.Value?.FirstOrDefault()?.FirstOrDefault(); + var barterSchemeItem = kvp.Value.FirstOrDefault()?.FirstOrDefault(); if ( barterSchemeItem?.Template != null && paymentHelper.IsMoneyTpl(barterSchemeItem.Template) diff --git a/Libraries/SPTarkov.Server.Core/DI/Router.cs b/Libraries/SPTarkov.Server.Core/DI/Router.cs index 70f1a72b..c8f74bd6 100644 --- a/Libraries/SPTarkov.Server.Core/DI/Router.cs +++ b/Libraries/SPTarkov.Server.Core/DI/Router.cs @@ -40,17 +40,8 @@ public abstract class Router } } -public abstract class StaticRouter : Router +public abstract class StaticRouter(JsonUtil jsonUtil, List routes) : Router { - private readonly List _actions; - private readonly JsonUtil _jsonUtil; - - public StaticRouter(JsonUtil jsonUtil, List routes) - { - _actions = routes; - _jsonUtil = jsonUtil; - } - public async ValueTask HandleStatic( string url, string? body, @@ -58,12 +49,12 @@ public abstract class StaticRouter : Router string output ) { - var action = _actions.Single(route => route.url == url); + var action = routes.Single(route => route.url == url); var type = action.bodyType; IRequestData? info = null; if (type != null && !string.IsNullOrEmpty(body)) { - info = (IRequestData?)_jsonUtil.Deserialize(body, type); + info = (IRequestData?)jsonUtil.Deserialize(body, type); } return await action.action(url, info, sessionId, output); @@ -71,7 +62,7 @@ public abstract class StaticRouter : Router protected override List GetHandledRoutes() { - return _actions.Select(route => new HandledRoute(route.url, false)).ToList(); + return routes.Select(route => new HandledRoute(route.url, false)).ToList(); } } diff --git a/Libraries/SPTarkov.Server.Core/Extensions/FullProfileExtensions.cs b/Libraries/SPTarkov.Server.Core/Extensions/FullProfileExtensions.cs index b6f013a7..4aec8c59 100644 --- a/Libraries/SPTarkov.Server.Core/Extensions/FullProfileExtensions.cs +++ b/Libraries/SPTarkov.Server.Core/Extensions/FullProfileExtensions.cs @@ -1,4 +1,5 @@ -using SPTarkov.Server.Core.Models.Eft.Common.Tables; +using SPTarkov.Server.Core.Models.Common; +using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Profile; using SPTarkov.Server.Core.Models.Enums; @@ -11,7 +12,7 @@ namespace SPTarkov.Server.Core.Extensions /// /// Profile to add clothing to /// Clothing Ids to add to profile - public static void AddSuitsToProfile(this SptProfile fullProfile, List clothingIds) + public static void AddSuitsToProfile(this SptProfile fullProfile, List clothingIds) { fullProfile.CustomisationUnlocks ??= []; diff --git a/Libraries/SPTarkov.Server.Core/Extensions/ItemExtensions.cs b/Libraries/SPTarkov.Server.Core/Extensions/ItemExtensions.cs index ba614748..295c8803 100644 --- a/Libraries/SPTarkov.Server.Core/Extensions/ItemExtensions.cs +++ b/Libraries/SPTarkov.Server.Core/Extensions/ItemExtensions.cs @@ -224,6 +224,7 @@ namespace SPTarkov.Server.Core.Extensions return list; } + /// /// Check if the passed in item has buy count restrictions /// /// Item to check diff --git a/Libraries/SPTarkov.Server.Core/Extensions/TemplateItemExtensions.cs b/Libraries/SPTarkov.Server.Core/Extensions/TemplateItemExtensions.cs index a60caca3..d9b9a837 100644 --- a/Libraries/SPTarkov.Server.Core/Extensions/TemplateItemExtensions.cs +++ b/Libraries/SPTarkov.Server.Core/Extensions/TemplateItemExtensions.cs @@ -27,7 +27,7 @@ namespace SPTarkov.Server.Core.Extensions /// /// Check if item is quest item /// - /// Items tpl to check quest status of + /// Item to check quest status of /// true if item is flagged as quest item public static bool IsQuestItem(this TemplateItem templateItem) { diff --git a/Libraries/SPTarkov.Server.Core/Extensions/UtilityExtensions.cs b/Libraries/SPTarkov.Server.Core/Extensions/UtilityExtensions.cs index f70ec2be..a8426b6f 100644 --- a/Libraries/SPTarkov.Server.Core/Extensions/UtilityExtensions.cs +++ b/Libraries/SPTarkov.Server.Core/Extensions/UtilityExtensions.cs @@ -5,9 +5,9 @@ public static List IntersectWith(this List first, List second) { //a.Intersect(x => b.Contains(x)).ToList(); - // gives error Delegate type could not be infered + // gives error Delegate type could not be inferred - return first.Where(x => second.Contains(x)).ToList(); + return first.Where(second.Contains).ToList(); } } } diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs index a5b3079b..08e86e73 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotEquipmentModGenerator.cs @@ -197,7 +197,8 @@ public class BotEquipmentModGenerator( ); switch (plateSlotFilteringOutcome.Result) { - case Result.UNKNOWN_FAILURE or Result.NO_DEFAULT_FILTER: + case Result.UNKNOWN_FAILURE + or Result.NO_DEFAULT_FILTER: if (logger.IsLogEnabled(LogLevel.Debug)) { logger.Debug( @@ -1373,10 +1374,9 @@ public class BotEquipmentModGenerator( // Limit how many attempts to find a compatible mod can occur before giving up var maxBlockedAttempts = Math.Round(modPool.Count * 0.75); // 75% of pool size var blockedAttemptCount = 0; - string chosenTpl; while (exhaustableModPool.HasValues()) { - chosenTpl = exhaustableModPool.GetRandomValue(); + var chosenTpl = exhaustableModPool.GetRandomValue(); var pickedItemDetails = itemHelper.GetItem(chosenTpl); if (!pickedItemDetails.Key) // Not valid item, try again @@ -1408,7 +1408,7 @@ public class BotEquipmentModGenerator( if (existingItemBlockingChoice is not null) { // Give max of x attempts of picking a mod if blocked by another - // OR Blocked and modpool only had 1 item + // OR Blocked and mod pool only had 1 item if (blockedAttemptCount > maxBlockedAttempts || modPool.Count == 1) { blockedAttemptCount = 0; // reset @@ -1420,11 +1420,10 @@ public class BotEquipmentModGenerator( blockedAttemptCount++; // Not compatible - Try again - ; continue; } - // Edge case- Some mod combos will never work, make sure this isnt the case + // Edge case - Some mod combos will never work, make sure this isn't the case if (WeaponModComboIsIncompatible(weapon, chosenTpl)) { chosenModResult.Reason = @@ -1492,12 +1491,7 @@ public class BotEquipmentModGenerator( } // Required mod is not default or randomisable, use existing pool - if (!request.ItemModPool.TryGetValue(request.ModSlot, out var modsForSlot)) - { - return null; - } - - return modsForSlot; + return request.ItemModPool.GetValueOrDefault(request.ModSlot); } /// @@ -1733,8 +1727,8 @@ public class BotEquipmentModGenerator( } } - // No mod found - return null; + // No mod found, return fallback + return tmpModTpl; } /// @@ -1774,7 +1768,7 @@ public class BotEquipmentModGenerator( } // Mod has invalid db item - if (!modToAdd.HasValue) + if (!modToAdd.Value.Key) { // Parent slot must be filled but db object is invalid, show warning and return false if (slotAddedToTemplate.Required ?? false) diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs index 2b361eb5..5ad62544 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotGenerator.cs @@ -29,7 +29,6 @@ public class BotGenerator( BotEquipmentFilterService botEquipmentFilterService, WeightedRandomHelper weightedRandomHelper, BotHelper botHelper, - BotGeneratorHelper botGeneratorHelper, SeasonalEventService seasonalEventService, ItemFilterService itemFilterService, BotNameService botNameService, diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs index b4a7f4ba..146b4760 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotInventoryGenerator.cs @@ -175,6 +175,7 @@ public class BotInventoryGenerator( /// Inventory to add equipment to /// Level of bot /// Game version for bot, only really applies for PMCs + /// Is the generated bot a PMC /// RadiConfig public void GenerateAndAddEquipmentToBot( MongoId sessionId, diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs index aaed1aaf..977a825b 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotLevelGenerator.cs @@ -1,3 +1,4 @@ +using System.Globalization; using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Bot; @@ -44,7 +45,8 @@ public class BotLevelGenerator( // Get random level based on the exp table. var exp = 0; var level = int.Parse( - ChooseBotLevel(botLevelRange.Min, botLevelRange.Max, 1, 1.15).ToString() + ChooseBotLevel(botLevelRange.Min, botLevelRange.Max, 1, 1.15) + .ToString(CultureInfo.InvariantCulture) ); // TODO - nasty double to string to int conversion for (var i = 0; i < level; i++) { diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs index 1dc439bb..87c27a2a 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotLootGenerator.cs @@ -765,10 +765,10 @@ public class BotLootGenerator( { var chosenWeaponType = randomUtil.GetArrayValue( [ - EquipmentSlots.FirstPrimaryWeapon.ToString(), - EquipmentSlots.FirstPrimaryWeapon.ToString(), - EquipmentSlots.FirstPrimaryWeapon.ToString(), - EquipmentSlots.Holster.ToString(), + nameof(EquipmentSlots.FirstPrimaryWeapon), + nameof(EquipmentSlots.FirstPrimaryWeapon), + nameof(EquipmentSlots.FirstPrimaryWeapon), + nameof(EquipmentSlots.Holster), ] ); var randomisedWeaponCount = randomUtil.GetInt( diff --git a/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs index 51b0b977..f04173be 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/BotWeaponGenerator.cs @@ -585,7 +585,7 @@ public class BotWeaponGenerator( { var id = new MongoId(); botGeneratorHelper.AddItemWithChildrenToEquipmentSlot( - new HashSet { EquipmentSlots.SecuredContainer }, + [EquipmentSlots.SecuredContainer], id, ammoTpl, new List @@ -658,7 +658,7 @@ public class BotWeaponGenerator( /// Dictionary of all cartridges keyed by type e.g. Caliber556x45NATO /// Weapon details from database we want to pick ammo for /// Ammo template that works with the desired gun - protected string? GetWeightedCompatibleAmmo( + protected MongoId GetWeightedCompatibleAmmo( Dictionary> cartridgePool, TemplateItem weaponTemplate ) @@ -686,7 +686,7 @@ public class BotWeaponGenerator( // Immediately returns, default ammo is guaranteed to be compatible // it is not guaranteed to even have a default ammo - return weaponTemplate.Properties.DefAmmo; + return weaponTemplate.Properties.DefAmmo.Value; } // Get cartridges the weapons first chamber allow @@ -696,7 +696,7 @@ public class BotWeaponGenerator( if (compatibleCartridgesInTemplate.Count == 0) // No chamber data found in weapon, send default { - return weaponTemplate.Properties.DefAmmo; + return weaponTemplate.Properties.DefAmmo.Value; } // Inner join the weapons allowed + passed in cartridge pool to get compatible cartridges @@ -719,7 +719,7 @@ public class BotWeaponGenerator( if (compatibleCartridgesInMagazine.Count == 0) { // No compatible cartridges found in magazine, use default - return weaponTemplate.Properties.DefAmmo; + return weaponTemplate.Properties.DefAmmo.Value; } // Get the caliber data from the first compatible round in the magazine @@ -739,7 +739,7 @@ public class BotWeaponGenerator( // Nothing found after also checking magazines, return default ammo if (compatibleCartridges.Count == 0) { - return weaponTemplate.Properties.DefAmmo; + return weaponTemplate.Properties.DefAmmo.Value; } } diff --git a/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs index 4fd2bb14..e8efea15 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/FenceBaseAssortGenerator.cs @@ -166,25 +166,16 @@ public class FenceBaseAssortGenerator( var itemAndChildren = _cloner.Clone(defaultPreset.Items).ReplaceIDs().ToList(); // Find root item and add some properties to it - for (var i = 0; i < itemAndChildren.Count; i++) + var rootItem = itemAndChildren.FirstOrDefault(item => + string.IsNullOrEmpty(item.ParentId) + ); + rootItem.ParentId = "hideout"; + rootItem.SlotId = "hideout"; + rootItem.Upd = new Upd { - var mod = itemAndChildren[i]; - - // Build root Item info - if (string.IsNullOrEmpty(mod.ParentId)) - { - mod.ParentId = "hideout"; - mod.SlotId = "hideout"; - mod.Upd = new Upd - { - StackObjectsCount = 1, - SptPresetId = defaultPreset.Id, // Store preset id here so we can check it later to prevent preset dupes - }; - - // Updated root item, exit loop - break; - } - } + StackObjectsCount = 1, + SptPresetId = defaultPreset.Id, // Store preset id here so we can check it later to prevent preset dupes + }; // Add constructed preset to assorts baseFenceAssort.Items.AddRange(itemAndChildren); @@ -294,10 +285,10 @@ public class FenceBaseAssortGenerator( foreach (var requiredSlot in requiredSlots) { var modItemDbDetails = itemHelper - .GetItem(requiredSlot.Props.Filters[0].Plate) + .GetItem(requiredSlot.Props.Filters[0].Plate.Value) .Value; var plateTpl = requiredSlot.Props.Filters[0].Plate; // `Plate` property appears to be the 'default' item for slot - if (string.IsNullOrEmpty(plateTpl)) + if (plateTpl is null) // Some bsg plate properties are empty, skip mod { continue; @@ -306,7 +297,7 @@ public class FenceBaseAssortGenerator( var mod = new Item { Id = new MongoId(), - Template = plateTpl, + Template = plateTpl.Value, ParentId = armor[0].Id, SlotId = requiredSlot.Name, Upd = new Upd @@ -338,12 +329,12 @@ public class FenceBaseAssortGenerator( continue; } - var modItemDbDetails = itemHelper.GetItem(plateTpl).Value; + var modItemDbDetails = itemHelper.GetItem(plateTpl.Value).Value; armor.Add( new Item { Id = new MongoId(), - Template = plateSlot.Props.Filters[0].Plate, // `Plate` property appears to be the 'default' item for slot + Template = plateSlot.Props.Filters[0].Plate.Value, // `Plate` property appears to be the 'default' item for slot ParentId = armor[0].Id, SlotId = plateSlot.Name, Upd = new Upd diff --git a/Libraries/SPTarkov.Server.Core/Generators/LootGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/LootGenerator.cs index 230419bf..884f663a 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/LootGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/LootGenerator.cs @@ -114,7 +114,9 @@ public class LootGenerator( if (randomisedWeaponPresetCount > 0) { var weaponDefaultPresets = globalDefaultPresets - .Where(preset => itemHelper.IsOfBaseclass(preset.Encyclopedia, BaseClasses.WEAPON)) + .Where(preset => + itemHelper.IsOfBaseclass(preset.Encyclopedia.Value, BaseClasses.WEAPON) + ) .ToList(); if (weaponDefaultPresets.Any()) @@ -145,7 +147,7 @@ public class LootGenerator( if (randomisedArmorPresetCount > 0) { var armorDefaultPresets = globalDefaultPresets.Where(preset => - itemHelper.ArmorItemCanHoldMods(preset.Encyclopedia) + itemHelper.ArmorItemCanHoldMods(preset.Encyclopedia.Value) ); var levelFilteredArmorPresets = armorDefaultPresets .Where(armor => IsArmorOfDesiredProtectionLevel(armor, options)) @@ -457,7 +459,7 @@ public class LootGenerator( } // Get preset root item db details via its `_encyclopedia` property - var itemDbDetails = itemHelper.GetItem(chosenPreset.Encyclopedia); + var itemDbDetails = itemHelper.GetItem(chosenPreset.Encyclopedia.Value); if (!itemDbDetails.Key) { if (logger.IsLogEnabled(LogLevel.Debug)) @@ -799,7 +801,7 @@ public class LootGenerator( ); } - public record ItemRewardPoolResults + protected record ItemRewardPoolResults { public List ItemPool { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs index 17594977..06abb0a5 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/PlayerScavGenerator.cs @@ -5,7 +5,6 @@ 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.Notes; using SPTarkov.Server.Core.Models.Enums; using SPTarkov.Server.Core.Models.Spt.Config; using SPTarkov.Server.Core.Models.Utils; @@ -114,7 +113,7 @@ public class PlayerScavGenerator( scavData.TaskConditionCounters = existingScavDataClone.TaskConditionCounters ?? new Dictionary(); - scavData.Notes = existingScavDataClone.Notes ?? new Notes { DataNotes = new List() }; + scavData.Notes = existingScavDataClone.Notes ?? new Notes { DataNotes = [] }; scavData.WishList = existingScavDataClone.WishList ?? new DictionaryOrList(new Dictionary(), []); @@ -379,34 +378,29 @@ public class PlayerScavGenerator( protected Stats GetScavStats(PmcData scavProfile) { - if (scavProfile?.Stats != null) - { - return scavProfile.Stats; - } - - return profileHelper.GetDefaultCounters(); + return scavProfile.Stats ?? profileHelper.GetDefaultCounters(); } protected int GetScavLevel(PmcData scavProfile) { // Info can be null on initial account creation - if (scavProfile?.Info?.Level == null) + if (scavProfile.Info?.Level == null) { return 1; } - return scavProfile?.Info?.Level ?? 1; + return scavProfile.Info?.Level ?? 1; } protected int GetScavExperience(PmcData scavProfile) { // Info can be null on initial account creation - if (scavProfile?.Info?.Experience == null) + if (scavProfile.Info?.Experience == null) { return 0; } - return scavProfile?.Info?.Experience ?? 0; + return scavProfile.Info?.Experience ?? 0; } /// @@ -432,7 +426,7 @@ public class PlayerScavGenerator( var scavLockDuration = databaseService.GetGlobals().Configuration.SavagePlayCooldown * modifier; - var fullProfile = profileHelper.GetFullProfile(pmcData?.SessionId); + var fullProfile = profileHelper.GetFullProfile(pmcData.SessionId.Value); if ( fullProfile?.ProfileInfo?.Edition?.StartsWith( AccountTypes.SPT_DEVELOPER, diff --git a/Libraries/SPTarkov.Server.Core/Generators/RepeatableQuestGeneration/RepeatableQuestRewardGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/RepeatableQuestGeneration/RepeatableQuestRewardGenerator.cs index 4da82d57..d9bae7e1 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/RepeatableQuestGeneration/RepeatableQuestRewardGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/RepeatableQuestGeneration/RepeatableQuestRewardGenerator.cs @@ -633,7 +633,7 @@ public class RepeatableQuestRewardGenerator( return new KeyValuePair( GeneratePresetReward( - chosenPreset.Encyclopedia, + chosenPreset.Encyclopedia.Value, 1, rewardIndex, chosenPreset.Items diff --git a/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs b/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs index 806afb3c..5b51a8a7 100644 --- a/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs +++ b/Libraries/SPTarkov.Server.Core/Generators/ScavCaseRewardGenerator.cs @@ -244,6 +244,7 @@ public class ScavCaseRewardGenerator( /// /// item pool to pick rewards from /// how the rewards should be filtered down (by item count) + /// Rarity of reward /// protected List PickRandomRewards( List items, diff --git a/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs index 35f8c8bb..69996822 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/BotGeneratorHelper.cs @@ -30,11 +30,11 @@ public class BotGeneratorHelper( // Equipment slot ids that do not conflict with other slots private static readonly FrozenSet _slotsWithNoCompatIssues = [ - EquipmentSlots.Scabbard.ToString(), - EquipmentSlots.Backpack.ToString(), - EquipmentSlots.SecuredContainer.ToString(), - EquipmentSlots.Holster.ToString(), - EquipmentSlots.ArmBand.ToString(), + nameof(EquipmentSlots.Scabbard), + nameof(EquipmentSlots.Backpack), + nameof(EquipmentSlots.SecuredContainer), + nameof(EquipmentSlots.Holster), + nameof(EquipmentSlots.ArmBand), ]; private static readonly string[] _pmcTypes = diff --git a/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs index 79b9adcb..c5cd8588 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/BotHelper.cs @@ -39,7 +39,7 @@ public class BotHelper( /// BotType object public BotType? GetBotTemplate(string role) { - if (!databaseService.GetBots().Types.TryGetValue(role?.ToLowerInvariant(), out var bot)) + if (!databaseService.GetBots().Types.TryGetValue(role.ToLowerInvariant(), out var bot)) { logger.Error($"Unable to get bot of type: {role} from DB"); @@ -69,12 +69,12 @@ public class BotHelper( public bool IsBotFollower(string botRole) { - return botRole?.StartsWith("follower", StringComparison.CurrentCultureIgnoreCase) ?? false; + return botRole.StartsWith("follower", StringComparison.CurrentCultureIgnoreCase); } public bool IsBotZombie(string botRole) { - return botRole?.StartsWith("infected", StringComparison.CurrentCultureIgnoreCase) ?? false; + return botRole.StartsWith("infected", StringComparison.CurrentCultureIgnoreCase); } /// @@ -87,7 +87,7 @@ public class BotHelper( const string friendlyBotTypesKey = "FRIENDLY_BOT_TYPES"; // Null guard - if (difficultySettings.Mind[friendlyBotTypesKey] is null) + if (!difficultySettings.Mind.ContainsKey(friendlyBotTypesKey)) { difficultySettings.Mind[friendlyBotTypesKey] = new List(); } @@ -105,13 +105,13 @@ public class BotHelper( const string revengePropKey = "REVENGE_BOT_TYPES"; // Nothing to add - if (typesToAdd is null) + if (typesToAdd.Length == 0) { return; } // Null guard - if (difficultySettings.Mind[revengePropKey] is null) + if (!difficultySettings.Mind.ContainsKey(revengePropKey)) { difficultySettings.Mind[revengePropKey] = new List(); } @@ -154,7 +154,7 @@ public class BotHelper( { // No randomisation details found, skip - return botEquipConfig?.Randomisation?.FirstOrDefault(randDetails => + return botEquipConfig.Randomisation?.FirstOrDefault(randDetails => botLevel >= randDetails.LevelRange.Min && botLevel <= randDetails.LevelRange.Max ); } diff --git a/Libraries/SPTarkov.Server.Core/Helpers/BotWeaponGeneratorHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/BotWeaponGeneratorHelper.cs index f1a23073..81d6f95d 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/BotWeaponGeneratorHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/BotWeaponGeneratorHelper.cs @@ -31,7 +31,7 @@ public class BotWeaponGeneratorHelper( { var randomizedMagazineCount = GetRandomizedMagazineCount(magCounts); var parentItem = itemHelper.GetItem(magTemplate.Parent).Value; - double? chamberBulletCount = 0; + double? chamberBulletCount; if (MagazineIsCylinderRelated(parentItem.Name)) { var firstSlotAmmoTpl = @@ -115,10 +115,8 @@ public class BotWeaponGeneratorHelper( HashSet? equipmentSlotsToAddTo = null ) { - if (equipmentSlotsToAddTo is null) - { - equipmentSlotsToAddTo = [EquipmentSlots.TacticalVest, EquipmentSlots.Pockets]; - } + // null guard input param + equipmentSlotsToAddTo ??= [EquipmentSlots.TacticalVest, EquipmentSlots.Pockets]; var ammoItems = itemHelper.SplitStack( new Item diff --git a/Libraries/SPTarkov.Server.Core/Helpers/CertificateHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/CertificateHelper.cs index d2c9a724..e9e43751 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/CertificateHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/CertificateHelper.cs @@ -16,7 +16,7 @@ public class CertificateHelper(ISptLogger logger, FileUtil fi //Todo: Finish off to match TS server /// - /// Currently not in use + /// Not currently in use /// /// /// @@ -85,17 +85,17 @@ public class CertificateHelper(ISptLogger logger, FileUtil fi /// private bool TryLoadCertificatePfx(out X509Certificate2? certificate) { - X509Certificate2 cert = null; if (!File.Exists(certificatePfxPath)) { - // file doesnt exist so create straight away - cert = GenerateSelfSignedCertificate("localhost"); + // file doesn't exist so create straight away + var cert = GenerateSelfSignedCertificate("localhost"); SaveCertificatePfx(cert); logger.Success($"Generated and stored self-signed certificate ({certificatePath})"); } try { + // TODO: //Archangel: For some reason despite this being deprecated this is the only way to load a certificate file //No idea why, I want to eventually switch over to the other format so it lines up with the TS server //But for now this works fine @@ -107,12 +107,7 @@ public class CertificateHelper(ISptLogger logger, FileUtil fi throw; } - if (certificate is not null) - { - return true; - } - - return false; + return certificate is not null; } /// diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/AbstractDialogChatBot.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/AbstractDialogChatBot.cs index e8baddc4..6024286c 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/AbstractDialogChatBot.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/AbstractDialogChatBot.cs @@ -22,7 +22,7 @@ public abstract class AbstractDialogChatBot( public async ValueTask HandleMessage(MongoId sessionId, SendMessageRequest request) { - if ((request.Text ?? "").Length == 0) + if (request.Text.Length == 0) { _logger.Error(localisationService.GetText("chatbot-command_was_empty")); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommands/GiveCommand/GiveSptCommand.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommands/GiveCommand/GiveSptCommand.cs index f6b8cbf2..5cfbcb3d 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommands/GiveCommand/GiveSptCommand.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/Commando/SptCommands/GiveCommand/GiveSptCommand.cs @@ -242,8 +242,12 @@ public class GiveSptCommand( { for (var i = 0; i < quantity; i++) { - List ammoBoxArray = []; - ammoBoxArray.Add(new Item { Id = new MongoId(), Template = checkedItem.Value.Id }); + List ammoBoxArray = + [ + new() { Id = new MongoId(), Template = checkedItem.Value.Id }, + // DO NOT generate the ammo box cartridges, the mail service does it for us! :) + // _itemHelper.addCartridgesToAmmoBox(ammoBoxArray, checkedItem[1]); + ]; // DO NOT generate the ammo box cartridges, the mail service does it for us! :) // _itemHelper.addCartridgesToAmmoBox(ammoBoxArray, checkedItem[1]); itemsToSend.AddRange(ammoBoxArray); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/FishMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/FishMessageHandler.cs index d0194744..ad5f1bf4 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/FishMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/FishMessageHandler.cs @@ -14,7 +14,7 @@ public class FishMessageHandler(MailSendService _mailSendService) : IChatMessage return 100; } - public bool CanHandle(string message) + public bool CanHandle(string? message) { return string.Equals(message, "fish", StringComparison.OrdinalIgnoreCase); } diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GarbageMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GarbageMessageHandler.cs index 40109808..706662e5 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GarbageMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/GarbageMessageHandler.cs @@ -3,13 +3,11 @@ using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common; using SPTarkov.Server.Core.Models.Eft.Profile; using SPTarkov.Server.Core.Services; -using SPTarkov.Server.Core.Utils; namespace SPTarkov.Server.Core.Helpers.Dialogue.SPTFriend.Commands; [Injectable] -public class GarbageMessageHandler(MailSendService _mailSendService, RandomUtil _randomUtil) - : IChatMessageHandler +public class GarbageMessageHandler(MailSendService _mailSendService) : IChatMessageHandler { public int GetPriority() { diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/HelloMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/HelloMessageHandler.cs index 5c8f2441..66c83fce 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/HelloMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/HelloMessageHandler.cs @@ -10,10 +10,10 @@ using SPTarkov.Server.Core.Utils; namespace SPTarkov.Server.Core.Helpers.Dialogue.SPTFriend.Commands; [Injectable] -public class HelloMessageHandler(MailSendService _mailSendService, RandomUtil _randomUtil) +public class HelloMessageHandler(MailSendService mailSendService, RandomUtil randomUtil) : IChatMessageHandler { - protected static readonly FrozenSet _listOfGreetings = + protected static readonly FrozenSet _greetings = [ "hello", "hi", @@ -30,7 +30,7 @@ public class HelloMessageHandler(MailSendService _mailSendService, RandomUtil _r public bool CanHandle(string message) { - return _listOfGreetings.Contains(message, StringComparer.OrdinalIgnoreCase); + return _greetings.Contains(message, StringComparer.OrdinalIgnoreCase); } public void Process( @@ -40,10 +40,10 @@ public class HelloMessageHandler(MailSendService _mailSendService, RandomUtil _r object? extraInfo = null ) { - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, sptFriendUser, - _randomUtil.GetArrayValue( + randomUtil.GetArrayValue( [ "Howdy", "Hi", @@ -84,10 +84,10 @@ public class HelloMessageHandler(MailSendService _mailSendService, RandomUtil _r SendMessageRequest request ) { - _mailSendService.SendUserMessageToPlayer( + mailSendService.SendUserMessageToPlayer( sessionId, commandHandler, - _randomUtil.GetArrayValue( + randomUtil.GetArrayValue( [ "Howdy", "Hi", diff --git a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs index d3eda002..1fca7ddd 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/Dialogue/SPTFriend/Commands/SendGiftMessageHandler.cs @@ -34,7 +34,7 @@ public class SendGiftMessageHandler( public void Process( MongoId sessionId, UserDialogInfo sptFriendUser, - PmcData sender, + PmcData? sender, object? extraInfo = null ) { diff --git a/Libraries/SPTarkov.Server.Core/Helpers/DialogueHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/DialogueHelper.cs index 11fe02cb..5ec16960 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/DialogueHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/DialogueHelper.cs @@ -72,10 +72,7 @@ public class DialogueHelper(ISptLogger logger, ProfileHelper pro // Check reward count when item being moved isn't in reward list // If count is 0, it means after this move occurs the reward array will be empty and all rewards collected - if (message.Items.Data is null) - { - message.Items.Data = []; - } + message.Items.Data ??= []; var messageItems = message.Items.Data?.Where(x => x.Id != itemId); if (messageItems is null || !messageItems.Any()) diff --git a/Libraries/SPTarkov.Server.Core/Helpers/HideoutHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/HideoutHelper.cs index 2f1bfb2e..695c9c48 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/HideoutHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/HideoutHelper.cs @@ -213,7 +213,7 @@ public class HideoutHelper( ); } - stashItem.Template = bonus.TemplateId; + stashItem.Template = bonus.TemplateId.Value; break; } @@ -869,9 +869,7 @@ public class HideoutHelper( var waterFilterItemInSlot = waterFilterArea.Slots[i].Items[0]; // How many units of filter are left - var resourceValue = waterFilterItemInSlot.Upd?.Resource is not null - ? waterFilterItemInSlot.Upd.Resource.Value - : null; + var resourceValue = waterFilterItemInSlot.Upd?.Resource?.Value; if (resourceValue is null) { // Missing, is new filter, add default and subtract usage @@ -1184,7 +1182,7 @@ public class HideoutHelper( // BSG finally fixed their settings, they now get loaded from the settings and used in the client var adjustedCraftTime = ( - profileHelper.IsDeveloperAccount(pmcData.SessionId) + profileHelper.IsDeveloperAccount(pmcData.SessionId.Value) ? 40 : bitcoinProdData.ProductionTime ) / (1 + (btcFarmCGs - 1) * databaseService.GetHideout().Settings.GpuBoostRate); @@ -1491,7 +1489,7 @@ public class HideoutHelper( /// /// Add/remove bonus combat skill based on number of dogtags in place of fame hideout area /// - /// Player profile + /// Player profile public void ApplyPlaceOfFameDogtagBonus(PmcData pmcData) { var fameAreaProfile = pmcData.Hideout.Areas.FirstOrDefault(area => diff --git a/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs index 36c3e030..cd968100 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/InventoryHelper.cs @@ -1171,7 +1171,7 @@ public class InventoryHelper( HandleCartridgeMove(sourceItems, request); // Get all children item has, they need to move with item - var idsToMove = sourceItems.FindAndReturnChildrenByItems(request.Item); + var idsToMove = sourceItems.FindAndReturnChildrenByItems(request.Item.Value); foreach (var itemId in idsToMove) { var itemToMove = sourceItems.FirstOrDefault(item => item.Id == itemId); @@ -1192,16 +1192,8 @@ public class InventoryHelper( itemToMove.ParentId = request.To.Id; itemToMove.SlotId = request.To.Container; - if (request.To.Location is not null) // Update location object - { - itemToMove.Location = request.To.Location; - } - else - // No location in request, delete it - { - itemToMove.Location = null; - } + itemToMove.Location = request.To.Location ?? null; // No location in request, delete it } toItems.Add(itemToMove); diff --git a/Libraries/SPTarkov.Server.Core/Helpers/PresetHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/PresetHelper.cs index 910f9144..3bb39511 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/PresetHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/PresetHelper.cs @@ -33,7 +33,9 @@ public class PresetHelper(DatabaseService databaseService, ItemHelper itemHelper var weapons = GetDefaultWeaponPresets(); var equipment = GetDefaultEquipmentPresets(); - return weapons.Union(equipment).ToDictionary(); + return weapons + .UnionBy(equipment, kvp => kvp.Key) + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } /// @@ -64,7 +66,7 @@ public class PresetHelper(DatabaseService databaseService, ItemHelper itemHelper _defaultWeaponPresets = tempPresets .Where(p => p.Value.Encyclopedia != null - && itemHelper.IsOfBaseclass(p.Value.Encyclopedia, BaseClasses.WEAPON) + && itemHelper.IsOfBaseclass(p.Value.Encyclopedia.Value, BaseClasses.WEAPON) ) .ToDictionary(); } @@ -84,7 +86,7 @@ public class PresetHelper(DatabaseService databaseService, ItemHelper itemHelper _defaultEquipmentPresets = tempPresets .Where(p => p.Value.Encyclopedia != null - && itemHelper.ArmorItemCanHoldMods(p.Value.Encyclopedia) + && itemHelper.ArmorItemCanHoldMods(p.Value.Encyclopedia.Value) ) .ToDictionary(); } @@ -115,7 +117,8 @@ public class PresetHelper(DatabaseService databaseService, ItemHelper itemHelper */ public bool IsPresetBaseClass(MongoId id, MongoId baseClass) { - return IsPreset(id) && itemHelper.IsOfBaseclass(GetPreset(id).Encyclopedia, baseClass); + return IsPreset(id) + && itemHelper.IsOfBaseclass(GetPreset(id).Encyclopedia.Value, baseClass); } /// diff --git a/Libraries/SPTarkov.Server.Core/Helpers/ProfileHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/ProfileHelper.cs index 0a4243b9..3eb8427f 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/ProfileHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/ProfileHelper.cs @@ -38,7 +38,7 @@ public class ProfileHelper( /// /// Remove/reset a completed quest condition from players profile quest data /// - /// Session id + /// Player profile /// Quest with condition to remove public void RemoveQuestConditionFromProfile( PmcData pmcData, @@ -273,7 +273,7 @@ public class ProfileHelper( { return new SearchFriendResponse { - Id = pmcProfile.Id, + Id = pmcProfile.Id.Value, Aid = pmcProfile.Aid, Info = new UserDialogDetails { diff --git a/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs index bb4450cf..ec72eb9a 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/QuestHelper.cs @@ -467,9 +467,7 @@ public class QuestHelper( // Include if quest found in profile and is started or ready to hand in return startedQuestInProfile is not null - && _startedOrAvailToFinish.Contains( - (QuestStatusEnum)startedQuestInProfile.Status - ); + && _startedOrAvailToFinish.Contains(startedQuestInProfile.Status); }); return GetQuestsWithOnlyLevelRequirementStartCondition(eligibleQuests).ToList(); @@ -616,7 +614,7 @@ public class QuestHelper( } /// - /// Sets the item stack to new value, or delete the item if value <= 0 + /// Sets the item stack to new value, or delete the item if value is less than or equal 0 /// /// Profile /// Id of item to adjust stack size of diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs index e1948fac..a136851b 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RagfairOfferHelper.cs @@ -181,7 +181,7 @@ public class RagfairOfferHelper( { // Get all offers that require the desired item and filter out offers from non traders if player below ragfair unlock var offerIDsForItem = ragfairRequiredItemsService.GetRequiredOffersById( - searchRequest.NeededSearchId + searchRequest.NeededSearchId.Value ); var tieredFlea = _ragfairConfig.TieredFlea; @@ -438,12 +438,7 @@ public class RagfairOfferHelper( return false; } - if ( - !assort.Items.Any(item => - { - return item.Id == offer.Root; - }) - ) + if (!assort.Items.Any(item => item.Id == offer.Root)) // skip (quest) locked items { return false; @@ -561,12 +556,12 @@ public class RagfairOfferHelper( /// true if out of stock protected bool TraderOutOfStock(RagfairOffer offer) { - if (offer?.Items?.Count == 0) + if (offer.Items?.Count == 0) { return true; } - return offer.Items[0]?.Upd?.StackObjectsCount == 0; + return offer.Items.FirstOrDefault()?.Upd?.StackObjectsCount == 0; } /// @@ -620,7 +615,7 @@ public class RagfairOfferHelper( protected HashSet GetLoyaltyLockedOffers(List offers, PmcData pmcProfile) { var loyaltyLockedOffers = new HashSet(); - foreach (var offer in offers.Where(offer => OfferIsFromTrader(offer))) + foreach (var offer in offers.Where(OfferIsFromTrader)) { if ( pmcProfile.TradersInfo.TryGetValue(offer.User.Id, out var traderDetails) @@ -645,7 +640,7 @@ public class RagfairOfferHelper( var profileOffers = GetProfileOffers(sessionId); // No offers, don't do anything - if (profileOffers?.Count == 0) + if (!profileOffers.Any()) { return true; } @@ -1078,7 +1073,7 @@ public class RagfairOfferHelper( var offerRootTemplate = itemHelper.GetItem(offerRootItem.Template).Value; var requiredPlateCount = offerRootTemplate .Properties.Slots?.Where(item => item.Required.GetValueOrDefault(false)) - ?.Count(); + .Count(); return offer.Items.Count > requiredPlateCount; } diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs index a21cb472..7be81df3 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RagfairSellHelper.cs @@ -1,3 +1,4 @@ +using System.Globalization; using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Models.Eft.Ragfair; using SPTarkov.Server.Core.Models.Spt.Config; @@ -141,7 +142,7 @@ public class RagfairSellHelper( if (logger.IsLogEnabled(LogLevel.Debug)) { logger.Debug( - $"Offer will sell at: {timeUtil.GetDateTimeFromTimeStamp(sellTimestamp).ToLocalTime().ToString()}, bought: {boughtAmount}" + $"Offer will sell at: {timeUtil.GetDateTimeFromTimeStamp(sellTimestamp).ToLocalTime().ToString(CultureInfo.InvariantCulture)}, bought: {boughtAmount}" ); } } diff --git a/Libraries/SPTarkov.Server.Core/Helpers/RagfairSortHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/RagfairSortHelper.cs index 6b85eada..efc15908 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/RagfairSortHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/RagfairSortHelper.cs @@ -37,7 +37,7 @@ public class RagfairSortHelper(LocaleService localeService) break; case RagfairSort.OFFER_TITLE: - offers.Sort((a, b) => SortOffersByName(a, b)); + offers.Sort(SortOffersByName); break; case RagfairSort.PRICE: @@ -79,8 +79,8 @@ public class RagfairSortHelper(LocaleService localeService) protected int SortOffersByRating(RagfairOffer a, RagfairOffer b) { - double ratingA = a?.User?.Rating ?? 0.0; - double ratingB = b?.User?.Rating ?? 0.0; + var ratingA = a.User?.Rating ?? 0.0; + var ratingB = b.User?.Rating ?? 0.0; return ratingA.CompareTo(ratingB); } @@ -94,7 +94,7 @@ public class RagfairSortHelper(LocaleService localeService) var nameA = locale.GetValueOrDefault($"{tplA} Name", tplA); var nameB = locale.GetValueOrDefault($"{tplB} Name", tplB); - return string.Compare(nameA, nameB); + return string.CompareOrdinal(nameA, nameB); } /** diff --git a/Libraries/SPTarkov.Server.Core/Helpers/TradeHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/TradeHelper.cs index 0cf76f56..e48a1bc7 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/TradeHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/TradeHelper.cs @@ -277,7 +277,7 @@ public class TradeHelper( return; } - /// Pay for purchase + // Pay for purchase paymentService.PayMoney(pmcData, buyRequestData, sessionID, output); if (output.Warnings?.Count > 0) { diff --git a/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs b/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs index ccd34a51..863dee8d 100644 --- a/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs +++ b/Libraries/SPTarkov.Server.Core/Helpers/TraderHelper.cs @@ -21,7 +21,6 @@ public class TraderHelper( DatabaseService databaseService, ProfileHelper profileHelper, HandbookHelper handbookHelper, - ItemHelper itemHelper, ServerLocalisationService serverLocalisationService, FenceService fenceService, TraderStore traderStore, @@ -451,6 +450,7 @@ public class TraderHelper( /// /// Session id /// New item assort id + count + /// Item purchased public void AddTraderPurchasesToPlayerProfile( MongoId sessionID, PurchaseDetails newPurchaseDetails, diff --git a/Libraries/SPTarkov.Server.Core/Loaders/BundleLoader.cs b/Libraries/SPTarkov.Server.Core/Loaders/BundleLoader.cs index d90ee68c..b32c0bca 100644 --- a/Libraries/SPTarkov.Server.Core/Loaders/BundleLoader.cs +++ b/Libraries/SPTarkov.Server.Core/Loaders/BundleLoader.cs @@ -43,35 +43,15 @@ public class BundleInfo } [Injectable(InjectionType.Singleton)] -public class BundleLoader +public class BundleLoader( + ISptLogger logger, + JsonUtil jsonUtil, + FileUtil fileUtil, + BundleHashCacheService bundleHashCacheService, + ICloner cloner +) { - private readonly BundleHashCacheService _bundleHashCacheService; private readonly Dictionary _bundles = new(); - private readonly ICloner _cloner; - private readonly FileUtil _fileUtil; - private readonly HashUtil _hashUtil; - private readonly InMemoryCacheService _inMemoryCacheService; - private readonly JsonUtil _jsonUtil; - private readonly ISptLogger _logger; - - public BundleLoader( - ISptLogger logger, - HashUtil hashUtil, - JsonUtil jsonUtil, - FileUtil fileUtil, - BundleHashCacheService bundleHashCacheService, - InMemoryCacheService inMemoryCacheService, - ICloner cloner - ) - { - _logger = logger; - _hashUtil = hashUtil; - _jsonUtil = jsonUtil; - _fileUtil = fileUtil; - _bundleHashCacheService = bundleHashCacheService; - _inMemoryCacheService = inMemoryCacheService; - _cloner = cloner; - } /// /// Handle singleplayer/bundles @@ -91,7 +71,7 @@ public class BundleLoader public BundleInfo? GetBundle(string bundleKey) { - return _cloner.Clone(_bundles.GetValueOrDefault(bundleKey)); + return cloner.Clone(_bundles.GetValueOrDefault(bundleKey)); } public void AddBundles(string modPath) @@ -99,10 +79,10 @@ public class BundleLoader // modPath should be relative to the server exe - ./user/mods/Mod3 // TODO: make sure the mod is passing a path that is relative from the server exe - var modBundlesJson = _fileUtil.ReadFile( + var modBundlesJson = fileUtil.ReadFile( Path.Join(Directory.GetCurrentDirectory(), modPath, "bundles.json") ); - var modBundles = _jsonUtil.Deserialize(modBundlesJson); + var modBundles = jsonUtil.Deserialize(modBundlesJson); var bundleManifestArr = modBundles?.Manifest; foreach (var bundleManifest in bundleManifestArr) @@ -112,12 +92,12 @@ public class BundleLoader var bundleLocalPath = Path.Join(relativeModPath, "bundles", bundleManifest.Key) .Replace('\\', '/'); - if (!_bundleHashCacheService.CalculateAndMatchHash(bundleLocalPath)) + if (!bundleHashCacheService.CalculateAndMatchHash(bundleLocalPath)) { - _bundleHashCacheService.CalculateAndStoreHash(bundleLocalPath); + bundleHashCacheService.CalculateAndStoreHash(bundleLocalPath); } - var bundleHash = _bundleHashCacheService.GetStoredValue(bundleLocalPath); + var bundleHash = bundleHashCacheService.GetStoredValue(bundleLocalPath); AddBundle( bundleManifest.Key, @@ -131,7 +111,7 @@ public class BundleLoader var success = _bundles.TryAdd(key, bundle); if (!success) { - _logger.Error($"Unable to add bundle: {key}"); + logger.Error($"Unable to add bundle: {key}"); } } } diff --git a/Libraries/SPTarkov.Server.Core/Migration/IProfileMigration.cs b/Libraries/SPTarkov.Server.Core/Migration/IProfileMigration.cs index 25beedc4..730975bd 100644 --- a/Libraries/SPTarkov.Server.Core/Migration/IProfileMigration.cs +++ b/Libraries/SPTarkov.Server.Core/Migration/IProfileMigration.cs @@ -9,6 +9,7 @@ namespace SPTarkov.Server.Core.Migration /// Allows for adding checks if the profile in question can migrate /// /// The profile to check + /// /// Returns true if the profile can migrate, returns false if not public bool CanMigrate( JsonObject profile, diff --git a/Libraries/SPTarkov.Server.Core/Migration/Migrations/TheVoices.cs b/Libraries/SPTarkov.Server.Core/Migration/Migrations/TheVoices.cs index 103b639c..efb96d92 100644 --- a/Libraries/SPTarkov.Server.Core/Migration/Migrations/TheVoices.cs +++ b/Libraries/SPTarkov.Server.Core/Migration/Migrations/TheVoices.cs @@ -1,7 +1,6 @@ using System.Text.Json.Nodes; using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.Services; -using Range = SemanticVersioning.Range; namespace SPTarkov.Server.Core.Migration.Migrations { diff --git a/Libraries/SPTarkov.Server.Core/Migration/Migrations/ThreeTenToThreeEleven.cs b/Libraries/SPTarkov.Server.Core/Migration/Migrations/ThreeTenToThreeEleven.cs index 0cb81d30..6c210d82 100644 --- a/Libraries/SPTarkov.Server.Core/Migration/Migrations/ThreeTenToThreeEleven.cs +++ b/Libraries/SPTarkov.Server.Core/Migration/Migrations/ThreeTenToThreeEleven.cs @@ -6,7 +6,6 @@ using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Profile; using SPTarkov.Server.Core.Models.Enums; using SPTarkov.Server.Core.Services; -using SPTarkov.Server.Core.Utils; using Range = SemanticVersioning.Range; namespace SPTarkov.Server.Core.Migration.Migrations @@ -77,10 +76,7 @@ namespace SPTarkov.Server.Core.Migration.Migrations profile.AddCustomisationUnlocksToProfile(); } - if (profile.CharacterData.PmcData.Prestige is null) - { - profile.CharacterData.PmcData.Prestige = []; - } + profile.CharacterData.PmcData.Prestige ??= []; if (profile.CharacterData.PmcData.Inventory.HideoutCustomizationStashId is null) { diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Globals.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Globals.cs index a24aaa17..f2750a7e 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Globals.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Globals.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Eft.Hideout; using SPTarkov.Server.Core.Models.Enums; @@ -5016,7 +5017,7 @@ public record Preset /// Default presets have this property /// [JsonPropertyName("_encyclopedia")] - public string? Encyclopedia { get; set; } + public MongoId? Encyclopedia { get; set; } } public record QuestSettings 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 76aa8378..c499a284 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/BotBase.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/BotBase.cs @@ -24,7 +24,7 @@ public record BotBase /// SPT property - use to store player id - TODO - move to AID ( account id as guid of choice) /// [JsonPropertyName("sessionId")] - public string? SessionId { get; set; } + public MongoId? SessionId { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.Never)] [JsonPropertyName("savage")] @@ -620,7 +620,7 @@ public record Aggressor public string? AccountId { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.Never)] - public string? ProfileId { get; set; } + public MongoId? ProfileId { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.Never)] public string? MainProfileNickname { get; set; } @@ -1039,7 +1039,7 @@ public record Bonus public BonusType? Type { get; set; } [JsonPropertyName("templateId")] - public string? TemplateId { get; set; } + public MongoId? TemplateId { get; set; } [JsonPropertyName("passive")] public bool? IsPassive { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomisationStorage.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomisationStorage.cs index 3d2eb63a..c7a484b9 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomisationStorage.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomisationStorage.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Common.Tables; @@ -9,7 +10,7 @@ public record CustomisationStorage // Customisation.json/itemId [JsonPropertyName("id")] - public string Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("source")] public string? Source { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomizationItem.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomizationItem.cs index 6e3f59bb..00206868 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomizationItem.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/CustomizationItem.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Common.Tables; @@ -56,13 +57,13 @@ public class CustomizationProps public List? Game { get; set; } [JsonPropertyName("Hands")] - public string? Hands { get; set; } + public MongoId? Hands { get; set; } [JsonPropertyName("Feet")] - public string? Feet { get; set; } + public MongoId? Feet { get; set; } [JsonPropertyName("Body")] - public string? Body { get; set; } + public MongoId? Body { get; set; } [JsonPropertyName("ProfileVersions")] public List? ProfileVersions { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Item.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Item.cs index c003be31..f3dd23cb 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Item.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Item.cs @@ -199,7 +199,7 @@ public record LockableComponent [JsonExtensionData] public Dictionary? ExtensionData { get; set; } - public string[]? KeyIds { get; set; } + public List? KeyIds { get; set; } public bool? Locked { get; set; } public LockableKeyComponent? KeyComponent { get; set; } } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/ProfileTemplate.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/ProfileTemplate.cs index bd4dbae7..10eba959 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/ProfileTemplate.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/ProfileTemplate.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Profile; namespace SPTarkov.Server.Core.Models.Eft.Common.Tables; @@ -27,7 +28,7 @@ public record TemplateSide public PmcData? Character { get; set; } [JsonPropertyName("suits")] - public List? Suits { get; set; } + public List? Suits { get; set; } [JsonPropertyName("dialogues")] public Dictionary? Dialogues { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/RepeatableQuests.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/RepeatableQuests.cs index 57e3e456..780a6a4d 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/RepeatableQuests.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/RepeatableQuests.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Common.Tables; @@ -150,7 +151,7 @@ public record ChangeCost /// What item it will take to reset daily /// [JsonPropertyName("templateId")] - public string? TemplateId { get; set; } + public MongoId TemplateId { get; set; } /// /// Amount of item needed to reset diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/TemplateItem.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/TemplateItem.cs index a3217fcd..80c32146 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/TemplateItem.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/TemplateItem.cs @@ -789,7 +789,7 @@ public record Props public MongoId? DefMagType { get; set; } [JsonPropertyName("defAmmo")] - public string? DefAmmo { get; set; } + public MongoId? DefAmmo { get; set; } [JsonPropertyName("AdjustCollimatorsToTrajectory")] public bool? AdjustCollimatorsToTrajectory { get; set; } @@ -1797,7 +1797,7 @@ public record SlotFilter public bool? Locked { get; set; } [JsonPropertyName("Plate")] - public string? Plate { get; set; } + public MongoId? Plate { get; set; } [JsonPropertyName("armorColliders")] public List? ArmorColliders { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Trader.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Trader.cs index c90bbebe..2637047c 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Trader.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Common/Tables/Trader.cs @@ -298,7 +298,7 @@ public record Suit public Dictionary? ExtensionData { get; set; } [JsonPropertyName("_id")] - public string? Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("externalObtain")] public bool? ExternalObtain { get; set; } @@ -310,10 +310,10 @@ public record Suit public bool? IsHiddenInPVE { get; set; } [JsonPropertyName("tid")] - public string? Tid { get; set; } + public MongoId Tid { get; set; } [JsonPropertyName("suiteId")] - public string? SuiteId { get; set; } + public MongoId SuiteId { get; set; } [JsonPropertyName("isActive")] public bool? IsActive { get; set; } @@ -356,7 +356,7 @@ public record SuitRequirements public List? ItemRequirements { get; set; } [JsonPropertyName("requiredTid")] - public string? RequiredTid { get; set; } + public MongoId? RequiredTid { get; set; } } public record ItemRequirement @@ -368,7 +368,7 @@ public record ItemRequirement public double? Count { get; set; } [JsonPropertyName("_tpl")] - public string? Tpl { get; set; } + public MongoId Tpl { get; set; } [JsonPropertyName("id")] public string? Id { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/BuyClothingRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/BuyClothingRequestData.cs index 73a30fd3..481ba62c 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/BuyClothingRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/BuyClothingRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Inventory; namespace SPTarkov.Server.Core.Models.Eft.Customization; @@ -24,7 +25,7 @@ public record PaymentItemForClothing public bool? Del { get; set; } [JsonPropertyName("id")] - public string? Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("count")] public int? Count { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/CustomizationSetRequest.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/CustomizationSetRequest.cs index c52af4f1..b9c068d7 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/CustomizationSetRequest.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Customization/CustomizationSetRequest.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Inventory; namespace SPTarkov.Server.Core.Models.Eft.Customization; @@ -18,7 +19,7 @@ public record CustomizationSetOption public Dictionary? ExtensionData { get; set; } [JsonPropertyName("id")] - public string? Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("type")] public string? Type { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutArea.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutArea.cs index aa1f3184..27eca3a9 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutArea.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutArea.cs @@ -77,7 +77,7 @@ public record Stage /// Containers inventory tpl /// [JsonPropertyName("container")] - public string? Container { get; set; } + public MongoId? Container { get; set; } [JsonPropertyName("description")] public string? Description { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutProduction.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutProduction.cs index ef441b21..beda1d5a 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutProduction.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Hideout/HideoutProduction.cs @@ -91,7 +91,7 @@ public record Requirement public int? Resource { get; set; } [JsonPropertyName("questId")] - public string? QuestId { get; set; } + public MongoId? QuestId { get; set; } [JsonPropertyName("isSpawnedInSession")] public bool? IsSpawnedInSession { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryFoldRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryFoldRequestData.cs index a39bc4c2..dd4fe737 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryFoldRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryFoldRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Inventory; @@ -8,7 +9,7 @@ public record InventoryFoldRequestData : InventoryBaseActionRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("item")] - public string? Item { get; set; } + public MongoId? Item { get; set; } [JsonPropertyName("value")] public bool? Value { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryMoveRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryMoveRequestData.cs index 62558f59..fe967fa0 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryMoveRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/InventoryMoveRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Inventory; @@ -8,7 +9,7 @@ public record InventoryMoveRequestData : InventoryBaseActionRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("item")] - public string? Item { get; set; } + public MongoId? Item { get; set; } [JsonPropertyName("to")] public To? To { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/OpenRandomLootContainerRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/OpenRandomLootContainerRequestData.cs index f9b3f00b..51069366 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/OpenRandomLootContainerRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/OpenRandomLootContainerRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Inventory; @@ -11,7 +12,7 @@ public record OpenRandomLootContainerRequestData : InventoryBaseActionRequestDat /// Container item id being opened /// [JsonPropertyName("item")] - public string? Item { get; set; } + public MongoId Item { get; set; } [JsonPropertyName("to")] public List? To { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/RedeemProfileRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/RedeemProfileRequestData.cs index 03681ae0..b37e4058 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/RedeemProfileRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Inventory/RedeemProfileRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Inventory; @@ -17,8 +18,8 @@ public record RedeemProfileRequestEvent public Dictionary? ExtensionData { get; set; } [JsonPropertyName("MessageId")] - public string? MessageId { get; set; } + public MongoId MessageId { get; set; } [JsonPropertyName("EventId")] - public string? EventId { get; set; } + public MongoId EventId { get; set; } } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Location/GetAirdropLootRequest.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Location/GetAirdropLootRequest.cs index 24123fbd..fa58243a 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Location/GetAirdropLootRequest.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Location/GetAirdropLootRequest.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Utils; namespace SPTarkov.Server.Core.Models.Eft.Location; @@ -9,5 +10,5 @@ public record GetAirdropLootRequest : IRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("containerId")] - public string? ContainerId { get; set; } + public MongoId ContainerId { get; set; } } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileChangeVoiceRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileChangeVoiceRequestData.cs index 346ccf77..966895fe 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileChangeVoiceRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileChangeVoiceRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Utils; namespace SPTarkov.Server.Core.Models.Eft.Profile; @@ -9,5 +10,5 @@ public record ProfileChangeVoiceRequestData : IRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("voice")] - public string? Voice { get; set; } + public MongoId Voice { get; set; } } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileCreateRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileCreateRequestData.cs index 29de1f75..002cf537 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileCreateRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/ProfileCreateRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Utils; namespace SPTarkov.Server.Core.Models.Eft.Profile; @@ -15,10 +16,10 @@ public record ProfileCreateRequestData : IRequestData public string? Nickname { get; set; } [JsonPropertyName("headId")] - public string? HeadId { get; set; } + public MongoId HeadId { get; set; } [JsonPropertyName("voiceId")] - public string? VoiceId { get; set; } + public MongoId VoiceId { get; set; } [JsonPropertyName("sptForcePrestigeLevel")] public int? SptForcePrestigeLevel { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SearchFriendResponse.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SearchFriendResponse.cs index 3f57bc4a..836d0fd6 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SearchFriendResponse.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SearchFriendResponse.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; namespace SPTarkov.Server.Core.Models.Eft.Profile; @@ -11,7 +12,7 @@ public record SearchFriendResponse public Dictionary? ExtensionData { get; set; } [JsonPropertyName("_id")] - public string? Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("aid")] public int? Aid { 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 e72ecc28..7a87ab00 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SptProfile.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Profile/SptProfile.cs @@ -57,7 +57,7 @@ public record SptProfile /// List of friend profile IDs /// [JsonPropertyName("friends")] - public List? FriendProfileIds { get; set; } + public List? FriendProfileIds { get; set; } /// /// Stores profile-related customisation, e.g. clothing / hideout walls / floors @@ -232,7 +232,7 @@ public record Dialogue public List? Messages { get; set; } [JsonPropertyName("_id")] - public string? Id { get; set; } + public MongoId Id { get; set; } } //TODO: @Cleanup: Maybe the same as Dialogue? @@ -557,7 +557,7 @@ public record BtrDelivery public Dictionary? ExtensionData { get; set; } [JsonPropertyName("_id")] - public string? Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("scheduledTime")] public int? ScheduledTime { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/AcceptQuestRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/AcceptQuestRequestData.cs index a9efbc3a..6bf1ef88 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/AcceptQuestRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/AcceptQuestRequestData.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Inventory; namespace SPTarkov.Server.Core.Models.Eft.Quests; @@ -9,7 +10,7 @@ public record AcceptQuestRequestData : InventoryBaseActionRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("qid")] - public string? QuestId { get; set; } + public MongoId QuestId { get; set; } [JsonPropertyName("type")] public string? Type { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/HandoverQuestRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/HandoverQuestRequestData.cs index df942eea..526f472d 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/HandoverQuestRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/HandoverQuestRequestData.cs @@ -10,10 +10,10 @@ public record HandoverQuestRequestData : InventoryBaseActionRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("qid")] - public string? QuestId { get; set; } + public MongoId QuestId { get; set; } [JsonPropertyName("conditionId")] - public string? ConditionId { get; set; } + public MongoId ConditionId { get; set; } [JsonPropertyName("items")] public List? Items { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/RepeatableQuestChangeEvent.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/RepeatableQuestChangeEvent.cs index a3cca6fb..e86229f0 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/RepeatableQuestChangeEvent.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Quests/RepeatableQuestChangeEvent.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Inventory; namespace SPTarkov.Server.Core.Models.Eft.Quests; @@ -9,5 +10,5 @@ public record RepeatableQuestChangeRequest : InventoryBaseActionRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("qid")] - public string? QuestId { get; set; } + public MongoId QuestId { get; set; } } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Ragfair/SearchRequestData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Ragfair/SearchRequestData.cs index feb1be74..883e3b10 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Ragfair/SearchRequestData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Ragfair/SearchRequestData.cs @@ -68,7 +68,7 @@ public record SearchRequestData : IRequestData public string? LinkedSearchId { get; set; } [JsonPropertyName("neededSearchId")] - public string? NeededSearchId { get; set; } + public MongoId? NeededSearchId { get; set; } [JsonPropertyName("buildItems")] public Dictionary? BuildItems { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/RepairActionDataRequest.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/RepairActionDataRequest.cs index 58759e2b..362662bc 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/RepairActionDataRequest.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/RepairActionDataRequest.cs @@ -28,7 +28,7 @@ public record RepairKitsInfo /// id of repair kit to use /// [JsonPropertyName("_id")] - public string? Id { get; set; } + public MongoId Id { get; set; } /// /// amount of units to reduce kit by diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/TraderRepairActionDataRequest.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/TraderRepairActionDataRequest.cs index c2cb06ed..a8e930c3 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/TraderRepairActionDataRequest.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Repair/TraderRepairActionDataRequest.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using SPTarkov.Server.Core.Models.Common; using SPTarkov.Server.Core.Models.Eft.Inventory; namespace SPTarkov.Server.Core.Models.Eft.Repair; @@ -9,7 +10,7 @@ public record TraderRepairActionDataRequest : InventoryBaseActionRequestData public Dictionary? ExtensionData { get; set; } [JsonPropertyName("tid")] - public string? TId { get; set; } + public MongoId TraderId { get; set; } [JsonPropertyName("repairItems")] public List? RepairItems { get; set; } @@ -21,7 +22,7 @@ public record RepairItem public Dictionary? ExtensionData { get; set; } [JsonPropertyName("_id")] - public string? Id { get; set; } + public MongoId Id { get; set; } [JsonPropertyName("count")] public double? Count { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Eft/Weather/WeatherData.cs b/Libraries/SPTarkov.Server.Core/Models/Eft/Weather/WeatherData.cs index 6956fef4..8bca6030 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Eft/Weather/WeatherData.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Eft/Weather/WeatherData.cs @@ -57,7 +57,7 @@ public record Weather public double? WindSpeed { get; set; } /// - /// < -0.4 = clear day + /// less than -0.4 = clear day /// [JsonPropertyName("cloud")] public double? Cloud { get; set; } diff --git a/Libraries/SPTarkov.Server.Core/Models/Spt/Bots/GenerateWeaponRequest.cs b/Libraries/SPTarkov.Server.Core/Models/Spt/Bots/GenerateWeaponRequest.cs index 5d084826..7d43315c 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Spt/Bots/GenerateWeaponRequest.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Spt/Bots/GenerateWeaponRequest.cs @@ -43,7 +43,7 @@ public record GenerateWeaponRequest /// Ammo tpl to use when generating magazines/cartridges /// [JsonPropertyName("ammoTpl")] - public string? AmmoTpl { get; set; } + public MongoId? AmmoTpl { get; set; } /// /// Bot-specific properties diff --git a/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/NewItemDetails.cs b/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/NewItemDetails.cs index eced0a90..f775d6e7 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/NewItemDetails.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Spt/Mod/NewItemDetails.cs @@ -79,7 +79,7 @@ public record CreateItemResult public CreateItemResult() { Success = false; - Errors = new List(); + Errors = []; } [JsonPropertyName("success")] diff --git a/Libraries/SPTarkov.Server.Core/Models/Spt/Services/InsuranceEquipmentPkg.cs b/Libraries/SPTarkov.Server.Core/Models/Spt/Services/InsuranceEquipmentPkg.cs index 9f27b52f..b65e542e 100644 --- a/Libraries/SPTarkov.Server.Core/Models/Spt/Services/InsuranceEquipmentPkg.cs +++ b/Libraries/SPTarkov.Server.Core/Models/Spt/Services/InsuranceEquipmentPkg.cs @@ -20,5 +20,5 @@ public record InsuranceEquipmentPkg public Item? ItemToReturnToPlayer { get; set; } [JsonPropertyName("traderId")] - public string? TraderId { get; set; } + public MongoId TraderId { get; set; } } diff --git a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/CustomizationItemEventRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/CustomizationItemEventRouter.cs index a2b93946..7d2ec842 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/CustomizationItemEventRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/CustomizationItemEventRouter.cs @@ -19,11 +19,11 @@ public class CustomizationItemEventRouter( { protected override List GetHandledRoutes() { - return new List - { + return + [ new(ItemEventActions.CUSTOMIZATION_BUY, false), new(ItemEventActions.CUSTOMIZATION_SET, false), - }; + ]; } public override ValueTask HandleItemEvent( diff --git a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/InsuranceItemEventRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/InsuranceItemEventRouter.cs index 36076815..befb56b5 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/InsuranceItemEventRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/InsuranceItemEventRouter.cs @@ -16,7 +16,7 @@ public class InsuranceItemEventRouter(InsuranceCallbacks insuranceCallbacks) { protected override List GetHandledRoutes() { - return new List { new(ItemEventActions.INSURE, false) }; + return [new(ItemEventActions.INSURE, false)]; } public override ValueTask HandleItemEvent( diff --git a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/NoteItemEventRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/NoteItemEventRouter.cs index a67cd90a..2c85b972 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/NoteItemEventRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/NoteItemEventRouter.cs @@ -15,12 +15,12 @@ public class NoteItemEventRouter(NoteCallbacks noteCallbacks) : ItemEventRouterD { protected override List GetHandledRoutes() { - return new List - { + return + [ new(ItemEventActions.ADD_NOTE, false), new(ItemEventActions.EDIT_NOTE, false), new(ItemEventActions.DELETE_NOTE, false), - }; + ]; } public override ValueTask HandleItemEvent( diff --git a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/QuestItemEventRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/QuestItemEventRouter.cs index 82ae1024..0adc6414 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/QuestItemEventRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/QuestItemEventRouter.cs @@ -15,13 +15,13 @@ public class QuestItemEventRouter(QuestCallbacks questCallbacks) : ItemEventRout { protected override List GetHandledRoutes() { - return new List - { + return + [ new(ItemEventActions.QUEST_ACCEPT, false), new(ItemEventActions.QUEST_COMPLETE, false), new(ItemEventActions.QUEST_HANDOVER, false), new(ItemEventActions.REPEATABLE_QUEST_CHANGE, false), - }; + ]; } public override ValueTask HandleItemEvent( diff --git a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/TradeItemEventRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/TradeItemEventRouter.cs index 4412595a..d2a91a85 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/TradeItemEventRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/ItemEvents/TradeItemEventRouter.cs @@ -15,12 +15,12 @@ public class TradeItemEventRouter(TradeCallbacks tradeCallbacks) : ItemEventRout { protected override List GetHandledRoutes() { - return new List - { + return + [ new(ItemEventActions.TRADING_CONFIRM, false), new(ItemEventActions.RAGFAIR_BUY_OFFER, false), new(ItemEventActions.SELL_ALL_FROM_SAVAGE, false), - }; + ]; } public override ValueTask HandleItemEvent( diff --git a/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InraidSaveLoadRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InraidSaveLoadRouter.cs index 9e143363..4fdfda39 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InraidSaveLoadRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InraidSaveLoadRouter.cs @@ -14,10 +14,7 @@ public class InraidSaveLoadRouter : SaveLoadRouter public override SptProfile HandleLoad(SptProfile profile) { - if (profile.InraidData == null) - { - profile.InraidData = new Inraid { Location = "none", Character = "none" }; - } + profile.InraidData ??= new Inraid { Location = "none", Character = "none" }; return profile; } diff --git a/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InsuranceSaveLoadRouter.cs b/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InsuranceSaveLoadRouter.cs index dd5f52d7..28fcca63 100644 --- a/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InsuranceSaveLoadRouter.cs +++ b/Libraries/SPTarkov.Server.Core/Routers/SaveLoad/InsuranceSaveLoadRouter.cs @@ -14,10 +14,7 @@ public class InsuranceSaveLoadRouter : SaveLoadRouter public override SptProfile HandleLoad(SptProfile profile) { - if (profile.InsuranceList == null) - { - profile.InsuranceList = new List(); - } + profile.InsuranceList ??= []; return profile; } diff --git a/Libraries/SPTarkov.Server.Core/Servers/Http/SptHttpListener.cs b/Libraries/SPTarkov.Server.Core/Servers/Http/SptHttpListener.cs index a1888aa7..8127204d 100644 --- a/Libraries/SPTarkov.Server.Core/Servers/Http/SptHttpListener.cs +++ b/Libraries/SPTarkov.Server.Core/Servers/Http/SptHttpListener.cs @@ -132,10 +132,7 @@ public class SptHttpListener( string output ) { - if (body == null) - { - body = new object(); - } + body ??= new object(); var bodyInfo = _jsonUtil.Serialize(body); @@ -235,7 +232,7 @@ public class SptHttpListener( { using (var ms = new MemoryStream()) { - using (var deflateStream = new ZLibStream(ms, CompressionLevel.SmallestSize)) + await using (var deflateStream = new ZLibStream(ms, CompressionLevel.SmallestSize)) { await deflateStream.WriteAsync(Encoding.UTF8.GetBytes(output)); } diff --git a/Libraries/SPTarkov.Server.Core/Servers/HttpServer.cs b/Libraries/SPTarkov.Server.Core/Servers/HttpServer.cs index e1c73dbe..853bbbed 100644 --- a/Libraries/SPTarkov.Server.Core/Servers/HttpServer.cs +++ b/Libraries/SPTarkov.Server.Core/Servers/HttpServer.cs @@ -31,8 +31,7 @@ public class HttpServer( /// /// Handle server loading event /// - /// Server builder - /// Throws Exception when WebApplicationBuiler or WebApplication are null + /// Throws Exception when WebApplicationBuilder or WebApplication are null public void Load() { if (_builder is null) diff --git a/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs b/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs index 22bcd4df..4ad246c4 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BotEquipmentFilterService.cs @@ -243,7 +243,8 @@ public class BotEquipmentFilterService( /// Prioritizes whitelist first, if one is found blacklist is ignored /// /// bot .json file to update - /// equipment blacklist + /// Equipment blacklist + /// Equipment whitelist /// Filtered bot file protected void FilterEquipment( BotType baseBotNode, @@ -381,6 +382,7 @@ public class BotEquipmentFilterService( /// /// Weighting change to apply to bot /// Bot item dictionary to adjust + /// OPTIONAL - show warnings when editing existing value protected void AdjustWeighting( AdjustmentDetails? weightingAdjustments, Dictionary> botItemPool, diff --git a/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs b/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs index 84a2345f..73021a58 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BotNameService.cs @@ -22,14 +22,17 @@ public class BotNameService( { protected readonly Lock _lockObject = new(); protected readonly BotConfig _botConfig = configServer.GetConfig(); - protected readonly HashSet _usedNameCache = new(); + protected readonly HashSet _usedNameCache = []; /// /// Clear out any entries in Name Set /// public void ClearNameCache() { - _usedNameCache.Clear(); + lock (_lockObject) + { + _usedNameCache.Clear(); + } } /// diff --git a/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs b/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs index e96e9484..b661258d 100644 --- a/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/BtrDeliveryService.cs @@ -71,10 +71,7 @@ public class BtrDeliveryService( .InsuredItems.Where(insuredItem => !deliveredItemIds.Contains(insuredItem.ItemId.Value)) .ToList(); - if (saveServer.GetProfile(sessionId).BtrDeliveryList == null) - { - saveServer.GetProfile(sessionId).BtrDeliveryList = new List(); - } + saveServer.GetProfile(sessionId).BtrDeliveryList ??= []; // Store delivery to send to player later in profile saveServer diff --git a/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs b/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs index 2e858d8a..9d73b0a6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/CircleOfCultistService.cs @@ -348,9 +348,10 @@ public class CircleOfCultistService( /// Items that can be picked /// Rouble budget to reach /// Id of stash item + /// /// Array of item arrays protected List> GetRewardsWithinBudget( - List rewardItemTplPool, + List rewardItemTplPool, double rewardBudget, MongoId cultistCircleStashId, CultistCircleSettings circleConfig @@ -543,6 +544,7 @@ public class CircleOfCultistService( /// /// sessionId /// Items sacrificed + /// /// Direct reward items to send to player protected DirectRewardSettings? CheckForDirectReward( MongoId sessionId, @@ -691,14 +693,14 @@ public class CircleOfCultistService( /// Do we return bonus items (hideout/task items) /// Circle config /// Array of tpls - protected List GetCultistCircleRewardPool( + protected List GetCultistCircleRewardPool( MongoId sessionId, PmcData pmcData, CircleCraftDetails craftingInfo, CultistCircleSettings cultistCircleConfig ) { - var rewardPool = new HashSet(); + var rewardPool = new HashSet(); var hideoutDbData = databaseService.GetHideout(); var itemsDb = databaseService.GetItems(); @@ -784,7 +786,7 @@ public class CircleOfCultistService( protected void AddTaskItemRequirementsToRewardPool( PmcData pmcData, HashSet itemRewardBlacklist, - HashSet rewardPool + HashSet rewardPool ) { var activeTasks = pmcData.Quests.Where(quest => quest.Status == QuestStatusEnum.Started); @@ -823,7 +825,7 @@ public class CircleOfCultistService( Hideout hideoutDbData, PmcData pmcData, HashSet itemRewardBlacklist, - HashSet rewardPool + HashSet rewardPool ) { var dbAreas = hideoutDbData.Areas; @@ -893,9 +895,8 @@ public class CircleOfCultistService( /// Reward pool to add to /// Item tpls to ignore /// Should these items meet the valuable threshold - /// Set of item tpls - protected HashSet GenerateRandomisedItemsAndAddToRewardPool( - HashSet rewardPool, + protected void GenerateRandomisedItemsAndAddToRewardPool( + HashSet rewardPool, HashSet itemRewardBlacklist, bool itemsShouldBeHighValue ) @@ -937,8 +938,6 @@ public class CircleOfCultistService( rewardPool.Add(randomItem.Id); currentItemCount++; } - - return rewardPool; } /// diff --git a/Libraries/SPTarkov.Server.Core/Services/CreateProfileService.cs b/Libraries/SPTarkov.Server.Core/Services/CreateProfileService.cs index d91ef3a9..8176dbe2 100644 --- a/Libraries/SPTarkov.Server.Core/Services/CreateProfileService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/CreateProfileService.cs @@ -195,9 +195,9 @@ public class CreateProfileService( || account.SptData?.PendingPrestige is not null ) { - var pendingPrestige = account.SptData.PendingPrestige is not null - ? account.SptData.PendingPrestige - : new PendingPrestige { PrestigeLevel = request.SptForcePrestigeLevel }; + var pendingPrestige = + account.SptData.PendingPrestige + ?? new PendingPrestige { PrestigeLevel = request.SptForcePrestigeLevel }; prestigeHelper.ProcessPendingPrestige(account, profileDetails, pendingPrestige); } diff --git a/Libraries/SPTarkov.Server.Core/Services/FenceService.cs b/Libraries/SPTarkov.Server.Core/Services/FenceService.cs index b0d50922..15d171c0 100644 --- a/Libraries/SPTarkov.Server.Core/Services/FenceService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/FenceService.cs @@ -1286,7 +1286,9 @@ public class FenceService( { foreach (var requiredSlot in softInsertSlots) { - var modItemDbDetails = itemHelper.GetItem(requiredSlot.Props.Filters[0].Plate).Value; + var modItemDbDetails = itemHelper + .GetItem(requiredSlot.Props.Filters[0].Plate.Value) + .Value; var durabilityValues = GetRandomisedArmorDurabilityValues( modItemDbDetails, @@ -1352,15 +1354,15 @@ public class FenceService( foreach (var plateSlot in plateSlots) { var plateTpl = plateSlot.Props.Filters[0].Plate; - if (string.IsNullOrEmpty(plateTpl)) - // Bsg data lacks a default plate, skip randomisng for this mod + if (plateTpl == null || plateTpl.Value.IsEmpty()) + // Bsg data lacks a default plate, skip randomising for this mod { continue; } var armorWithMods = armorItemAndMods; - var modItemDbDetails = itemHelper.GetItem(plateTpl).Value; + var modItemDbDetails = itemHelper.GetItem(plateTpl.Value).Value; // Chance to remove plate var plateExistsChance = traderConfig.Fence.ChancePlateExistsInArmorPercent[ @@ -1725,7 +1727,7 @@ public class FenceService( /// /// Player profile /// FenceLevel object - public FenceLevel GetFenceInfo(PmcData pmcData) + public FenceLevel? GetFenceInfo(PmcData pmcData) { var fenceSettings = databaseService.GetGlobals().Configuration.FenceSettings; if (!pmcData.TradersInfo.TryGetValue(fenceSettings.FenceIdentifier, out var pmcFenceInfo)) @@ -1748,7 +1750,7 @@ public class FenceService( return fenceSettings.Levels[maxLevel]; } - return fenceSettings.Levels[pmcFenceLevel]; + return fenceSettings.Levels.GetValueOrDefault(pmcFenceLevel); } /// diff --git a/Libraries/SPTarkov.Server.Core/Services/GiftService.cs b/Libraries/SPTarkov.Server.Core/Services/GiftService.cs index 41de7857..aa7a0ed6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/GiftService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/GiftService.cs @@ -65,7 +65,7 @@ public class GiftService( /// Player to send gift to / sessionID /// ID of gift in configs/gifts.json to send player /// Outcome of sending gift to player - public GiftSentResult SendGiftToPlayer(string playerId, string giftId) + public GiftSentResult SendGiftToPlayer(MongoId playerId, string giftId) { var giftData = GetGiftById(giftId); if (giftData is null) @@ -130,28 +130,14 @@ public class GiftService( } else if (giftData.Sender == GiftSenderType.Trader) { - if (giftData.LocaleTextId is not null) - { - mailSendService.SendLocalisedNpcMessageToPlayer( - playerId, - giftData.Trader, - MessageType.MessageWithItems, - giftData.LocaleTextId, - giftData.Items, - timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1) - ); - } - else - { - mailSendService.SendLocalisedNpcMessageToPlayer( - playerId, - giftData.Trader, - MessageType.MessageWithItems, - giftData.MessageText, - giftData.Items, - timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1) - ); - } + mailSendService.SendLocalisedNpcMessageToPlayer( + playerId, + giftData.Trader, + MessageType.MessageWithItems, + giftData.LocaleTextId ?? giftData.LocaleTextId, + giftData.Items, + timeUtil.GetHoursAsSeconds(giftData.CollectionTimeHours ?? 1) + ); } else { @@ -262,9 +248,9 @@ public class GiftService( /// ID of gift to send /// Session ID of player to send to /// Optional, how many to send - public void SendGiftWithSilentReceivedCheck(string giftId, MongoId? sessionId, int giftCount) + public void SendGiftWithSilentReceivedCheck(string giftId, MongoId sessionId, int giftCount) { - if (!profileHelper.PlayerHasReceivedMaxNumberOfGift(sessionId.Value, giftId, giftCount)) + if (!profileHelper.PlayerHasReceivedMaxNumberOfGift(sessionId, giftId, giftCount)) { SendGiftToPlayer(sessionId, giftId); } diff --git a/Libraries/SPTarkov.Server.Core/Services/InMemoryCacheService.cs b/Libraries/SPTarkov.Server.Core/Services/InMemoryCacheService.cs index 813ec2e6..fa00a13e 100644 --- a/Libraries/SPTarkov.Server.Core/Services/InMemoryCacheService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/InMemoryCacheService.cs @@ -25,9 +25,9 @@ public class InMemoryCacheService(ICloner cloner) /// Stored data public T? GetDataByKey(string key) { - if (_cacheData.ContainsKey(key)) + if (_cacheData.TryGetValue(key, out var value)) { - return (T)_cacheData[key]; + return (T)value; } return default; diff --git a/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs b/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs index 274cbdeb..719da262 100644 --- a/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/InsuranceService.cs @@ -229,6 +229,7 @@ public class InsuranceService( /// /// Store lost gear post-raid inside profile, ready for later code to pick it up and mail it /// + /// Player/session id /// Gear to store - generated by GetGearLostInRaid() public void StoreGearLostInRaidToSendLater( MongoId sessionID, @@ -338,12 +339,9 @@ public class InsuranceService( AddInsuranceItemToArray(sessionId, traderId, itemToReturnToPlayer); - // Remove item from insured items array as its been processed + // Remove item from insured items array as it has been processed pmcData.InsuredItems = pmcData - .InsuredItems.Where(item => - { - return item.ItemId != itemToReturnToPlayer.Id; - }) + .InsuredItems.Where(item => item.ItemId != itemToReturnToPlayer.Id) .ToList(); } diff --git a/Libraries/SPTarkov.Server.Core/Services/ItemBaseClassService.cs b/Libraries/SPTarkov.Server.Core/Services/ItemBaseClassService.cs index 25508454..db2246a5 100644 --- a/Libraries/SPTarkov.Server.Core/Services/ItemBaseClassService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/ItemBaseClassService.cs @@ -141,11 +141,11 @@ public class ItemBaseClassService( HydrateItemBaseClassCache(); } - if (!_itemBaseClassesCache.ContainsKey(itemTpl)) + if (!_itemBaseClassesCache.TryGetValue(itemTpl, out var value)) { return []; } - return _itemBaseClassesCache[itemTpl].ToList(); + return value.ToList(); } } diff --git a/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs b/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs index 1dda80a2..ec51209b 100644 --- a/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/LocationLifecycleService.cs @@ -49,12 +49,12 @@ public class LocationLifecycleService( BtrDeliveryService btrDeliveryService ) { - protected LocationConfig _locationConfig = configServer.GetConfig(); - protected InRaidConfig _inRaidConfig = configServer.GetConfig(); - protected TraderConfig _traderConfig = configServer.GetConfig(); - protected RagfairConfig _ragfairConfig = configServer.GetConfig(); - protected HideoutConfig _hideoutConfig = configServer.GetConfig(); - protected PmcConfig _pmcConfig = configServer.GetConfig(); + protected readonly LocationConfig _locationConfig = configServer.GetConfig(); + protected readonly InRaidConfig _inRaidConfig = configServer.GetConfig(); + protected readonly TraderConfig _traderConfig = configServer.GetConfig(); + protected readonly RagfairConfig _ragfairConfig = configServer.GetConfig(); + protected readonly HideoutConfig _hideoutConfig = configServer.GetConfig(); + protected readonly PmcConfig _pmcConfig = configServer.GetConfig(); /// /// Handle client/match/local/start diff --git a/Libraries/SPTarkov.Server.Core/Services/MailSendService.cs b/Libraries/SPTarkov.Server.Core/Services/MailSendService.cs index 10d61968..513a0174 100644 --- a/Libraries/SPTarkov.Server.Core/Services/MailSendService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/MailSendService.cs @@ -114,7 +114,7 @@ public class MailSendService( /// public void SendLocalisedNpcMessageToPlayer( MongoId sessionId, - string? trader, + MongoId? trader, MessageType messageType, string messageLocaleId, List? items, diff --git a/Libraries/SPTarkov.Server.Core/Services/MapMarkerService.cs b/Libraries/SPTarkov.Server.Core/Services/MapMarkerService.cs index 076eff54..188e4a14 100644 --- a/Libraries/SPTarkov.Server.Core/Services/MapMarkerService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/MapMarkerService.cs @@ -22,7 +22,7 @@ public class MapMarkerService(ISptLogger logger) var mapItem = pmcData?.Inventory?.Items?.FirstOrDefault(i => i?.Id == request?.Item); // add marker to map item - mapItem.Upd.Map = mapItem?.Upd?.Map ?? new UpdMap { Markers = new List() }; + mapItem.Upd.Map = mapItem?.Upd?.Map ?? new UpdMap { Markers = [] }; // Update request note with text, then add to maps upd request.MapMarker.Note = SanitiseMapMarkerText(request.MapMarker.Note); @@ -44,10 +44,7 @@ public class MapMarkerService(ISptLogger logger) // remove marker var markers = mapItem - .Upd.Map.Markers.Where(marker => - { - return marker.X != request.X && marker.Y != request.Y; - }) + .Upd.Map.Markers.Where(marker => marker.X != request.X && marker.Y != request.Y) .ToList(); mapItem.Upd.Map.Markers = markers; diff --git a/Libraries/SPTarkov.Server.Core/Services/Mod/CustomItemService.cs b/Libraries/SPTarkov.Server.Core/Services/Mod/CustomItemService.cs index 211d1fd4..d493bb1e 100644 --- a/Libraries/SPTarkov.Server.Core/Services/Mod/CustomItemService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/Mod/CustomItemService.cs @@ -38,9 +38,9 @@ public class CustomItemService( var newItemId = GetOrGenerateIdForItem(newItemDetails.NewId); // Fail if itemId already exists - if (tables.Templates.Items.ContainsKey(newItemId)) + if (tables.Templates.Items.TryGetValue(newItemId, out var item)) { - result.Errors.Add($"ItemId already exists. {tables.Templates.Items[newItemId].Name}"); + result.Errors.Add($"ItemId already exists. {item.Name}"); result.Success = false; result.ItemId = newItemId; @@ -102,9 +102,9 @@ public class CustomItemService( var newItem = newItemDetails.NewItem; // Fail if itemId already exists - if (tables.Templates.Items.ContainsKey(newItem.Id)) + if (tables.Templates.Items.TryGetValue(newItem.Id, out var item)) { - result.Errors.Add($"ItemId already exists. {tables.Templates.Items[newItem.Id].Name}"); + result.Errors.Add($"ItemId already exists. {item.Name}"); return result; } @@ -221,7 +221,7 @@ public class CustomItemService( /// ID of the item being added /// Parent ID of the item being added /// Price of the item being added - protected void AddToHandbookDb(string newItemId, string parentId, double? priceRoubles) + protected void AddToHandbookDb(MongoId newItemId, string parentId, double? priceRoubles) { databaseService .GetTemplates() diff --git a/Libraries/SPTarkov.Server.Core/Services/PmcChatResponseService.cs b/Libraries/SPTarkov.Server.Core/Services/PmcChatResponseService.cs index ce06854d..895cdd54 100644 --- a/Libraries/SPTarkov.Server.Core/Services/PmcChatResponseService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/PmcChatResponseService.cs @@ -99,7 +99,7 @@ public class PmcChatResponseService( var killerDetails = new UserDialogInfo { - Id = killer.ProfileId, + Id = killer.ProfileId.Value, Aid = killerDetailsInCache.Aid, Info = new UserDialogDetails { diff --git a/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs b/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs index ba8f2876..83b5b383 100644 --- a/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/PostDbLoadService.cs @@ -280,7 +280,7 @@ public class PostDbLoadService( private void RemovePraporTestMessage() { - foreach ((var locale, var lazyLoad) in databaseService.GetLocales().Global) + foreach (var (locale, lazyLoad) in databaseService.GetLocales().Global) { lazyLoad.AddTransformer(lazyloadedData => { diff --git a/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs b/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs index 0513ed26..398fcae9 100644 --- a/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/ProfileFixerService.cs @@ -134,7 +134,7 @@ public class ProfileFixerService( else { // Items are different, replace ID with unique value - // Only replace ID if items have no children, we dont want orphaned children + // Only replace ID if items have no children, we don't want orphaned children var itemsHaveChildren = pmcProfile.Inventory.Items.Any(x => x.ParentId == mappingKvP.Key ); @@ -428,10 +428,8 @@ public class ProfileFixerService( // Add above match to pmc profile var matchingProductionId = matchingProductions[0].Id; - if (!pmcProfile.UnlockedInfo.UnlockedProductionRecipe.Contains(matchingProductionId)) + if (pmcProfile.UnlockedInfo.UnlockedProductionRecipe.Add(matchingProductionId)) { - pmcProfile.UnlockedInfo.UnlockedProductionRecipe.Add(matchingProductionId); - if (logger.IsLogEnabled(LogLevel.Debug)) { logger.Debug( @@ -677,30 +675,19 @@ public class ProfileFixerService( if (fullProfile.UserBuildData is not null) { // Remove invalid builds from weapon, equipment and magazine build lists - var weaponBuilds = fullProfile.UserBuildData?.WeaponBuilds ?? new List(); + var weaponBuilds = fullProfile.UserBuildData?.WeaponBuilds ?? []; fullProfile.UserBuildData.WeaponBuilds = weaponBuilds - .Where(build => - { - return !ShouldRemoveWeaponEquipmentBuild("weapon", build, itemsDb); - }) + .Where(build => !ShouldRemoveWeaponEquipmentBuild("weapon", build, itemsDb)) .ToList(); - var equipmentBuilds = - fullProfile.UserBuildData.EquipmentBuilds ?? new List(); + var equipmentBuilds = fullProfile.UserBuildData.EquipmentBuilds ?? []; fullProfile.UserBuildData.EquipmentBuilds = equipmentBuilds - .Where(build => - { - return !ShouldRemoveWeaponEquipmentBuild("equipment", build, itemsDb); - }) + .Where(build => !ShouldRemoveWeaponEquipmentBuild("equipment", build, itemsDb)) .ToList(); - var magazineBuild = - fullProfile.UserBuildData.MagazineBuilds ?? new List(); + var magazineBuild = fullProfile.UserBuildData.MagazineBuilds ?? []; fullProfile.UserBuildData.MagazineBuilds = magazineBuild - .Where(build => - { - return !ShouldRemoveMagazineBuild(build, itemsDb); - }) + .Where(build => !ShouldRemoveMagazineBuild(build, itemsDb)) .ToList(); } @@ -753,9 +740,11 @@ public class ProfileFixerService( var clothingDb = databaseService.GetTemplates().Customization; foreach ( - var clothingItem in fullProfile.CustomisationUnlocks.Where(customisation => - customisation.Type == CustomisationType.SUITE - ) + var clothingItem in fullProfile + .CustomisationUnlocks.Where(customisation => + customisation.Type == CustomisationType.SUITE + ) + .ToList() // We're removing element, ToList to allow that to occur ) { if (!clothingDb.ContainsKey(clothingItem.Id)) @@ -775,10 +764,7 @@ public class ProfileFixerService( } } - foreach ( - var repeatable in fullProfile.CharacterData.PmcData.RepeatableQuests - ?? new List() - ) + foreach (var repeatable in fullProfile.CharacterData.PmcData.RepeatableQuests ?? []) { if (repeatable.ActiveQuests is null) { diff --git a/Libraries/SPTarkov.Server.Core/Services/ProfileMigratorService.cs b/Libraries/SPTarkov.Server.Core/Services/ProfileMigratorService.cs index 30733f20..34a2be92 100644 --- a/Libraries/SPTarkov.Server.Core/Services/ProfileMigratorService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/ProfileMigratorService.cs @@ -1,7 +1,6 @@ using System.Text.Json; using System.Text.Json.Nodes; using SPTarkov.DI.Annotations; -using SPTarkov.Server.Core.Helpers; using SPTarkov.Server.Core.Migration; using SPTarkov.Server.Core.Models.Eft.Profile; using SPTarkov.Server.Core.Models.Utils; @@ -41,7 +40,6 @@ namespace SPTarkov.Server.Core.Services ?? throw new InvalidOperationException( $"Could not deserialize the profile {profileId}" ); - ; } var ranMigrations = new List(); @@ -89,13 +87,6 @@ namespace SPTarkov.Server.Core.Services return SptReadyProfile; } - protected void SetCompletedMigration(JsonObject profile, string migrationName) - { - var profileMigrations = profile["spt"]["migrations"] as JsonObject; - - profileMigrations[migrationName] = JsonValue.Create(timeUtil.GetTimeStamp()); - } - protected IEnumerable SortMigrations() { var sortedMigrations = new List(); diff --git a/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs b/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs index 722a10d5..a72a0733 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RagfairOfferService.cs @@ -288,7 +288,7 @@ public class RagfairOfferService( ); notificationSendHelper.SendMessage(offerCreatorId, notificationMessage); - ragfairServerHelper.ReturnItems(offerCreatorProfile.SessionId, unstackedItems); + ragfairServerHelper.ReturnItems(offerCreatorProfile.SessionId.Value, unstackedItems); offerCreatorProfile.RagfairInfo.Offers.Splice(indexOfOfferInProfile, 1); if (logger.IsLogEnabled(LogLevel.Debug)) diff --git a/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs b/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs index d0d2108d..f04578e6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RagfairPriceService.cs @@ -523,7 +523,7 @@ public class RagfairPriceService( /// Attempt to get the default preset for a weapon, failing that get the first preset in the array /// (assumes default = has encyclopedia entry) /// - /// weapon presets to choose from + /// weapon item to get preset of /// Default preset object protected WeaponPreset GetWeaponPreset(Item weapon) { diff --git a/Libraries/SPTarkov.Server.Core/Services/RagfairTaxService.cs b/Libraries/SPTarkov.Server.Core/Services/RagfairTaxService.cs index 85c2646d..dfd3a602 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RagfairTaxService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RagfairTaxService.cs @@ -108,9 +108,7 @@ public class RagfairTaxService( itemWorth * itemTaxMult * itemPriceMult + requirementsPrice * requirementTaxMult * requirementPriceMult; var discountedTax = tax * (1.0 - taxDiscountPercent); - var itemComissionMult = itemTemplate.Properties.RagFairCommissionModifier.HasValue - ? itemTemplate.Properties.RagFairCommissionModifier.Value - : 1; + var itemComissionMult = itemTemplate.Properties.RagFairCommissionModifier ?? 1; if (item.Upd.Buff is not null) { diff --git a/Libraries/SPTarkov.Server.Core/Services/RepairService.cs b/Libraries/SPTarkov.Server.Core/Services/RepairService.cs index 7376ddc6..a98659e6 100644 --- a/Libraries/SPTarkov.Server.Core/Services/RepairService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/RepairService.cs @@ -608,7 +608,6 @@ public class RepairService( /// Check if item should be buffed by checking the item type and relevant player skill level /// /// Item that was repaired - /// tpl of item to be buffed /// Player profile /// True if item should have buff applied protected bool ShouldBuffItem(RepairDetails repairDetails, PmcData pmcData) diff --git a/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs b/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs index 23839f45..41834952 100644 --- a/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs +++ b/Libraries/SPTarkov.Server.Core/Services/SeasonalEventService.cs @@ -214,7 +214,7 @@ public class SeasonalEventService( /// /// Get a dictionary of loot changes to apply to bots for a specific event e.g. Christmas/Halloween /// - /// Name of event to get gear changes for + /// Name of event to get gear changes for /// bots with loot changes protected Dictionary>> GetEventBotLoot( SeasonalEventType eventType @@ -290,7 +290,7 @@ public class SeasonalEventService( var seasonalEvents = GetEventDetails(); // reset existing data - _currentlyActiveEvents = new List(); + _currentlyActiveEvents = []; // Add active events to array foreach (var events in seasonalEvents) diff --git a/Libraries/SPTarkov.Server.Core/Utils/App.cs b/Libraries/SPTarkov.Server.Core/Utils/App.cs index cde35517..c352020a 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/App.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/App.cs @@ -27,8 +27,8 @@ public class App( HttpServerHelper _httpServerHelper ) { - protected CoreConfig _coreConfig = _configServer.GetConfig(); - protected Dictionary _onUpdateLastRun = new(); + protected readonly CoreConfig _coreConfig = _configServer.GetConfig(); + protected readonly Dictionary _onUpdateLastRun = new(); public async Task InitializeAsync() { diff --git a/Libraries/SPTarkov.Server.Core/Utils/Cloners/JsonCloner.cs b/Libraries/SPTarkov.Server.Core/Utils/Cloners/JsonCloner.cs index 629a99e7..d72f33b8 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Cloners/JsonCloner.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Cloners/JsonCloner.cs @@ -3,17 +3,10 @@ namespace SPTarkov.Server.Core.Utils.Cloners; /// /// Disabled as FastCloner library is 15% faster and consumes less memory than Json serialization /// -public class JsonCloner : ICloner +public class JsonCloner(JsonUtil jsonUtil) : ICloner { - protected JsonUtil _jsonUtil; - - public JsonCloner(JsonUtil jsonUtil) - { - _jsonUtil = jsonUtil; - } - public T? Clone(T? obj) { - return _jsonUtil.Deserialize(_jsonUtil.Serialize(obj)); + return jsonUtil.Deserialize(jsonUtil.Serialize(obj)); } } diff --git a/Libraries/SPTarkov.Server.Core/Utils/Cloners/ReflectionsCloner.cs b/Libraries/SPTarkov.Server.Core/Utils/Cloners/ReflectionsCloner.cs index e654249a..9dd439b0 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Cloners/ReflectionsCloner.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Cloners/ReflectionsCloner.cs @@ -85,10 +85,7 @@ public class ReflectionsCloner(ISptLogger logger) : ICloner "Add", BindingFlags.Instance | BindingFlags.Public ); - while (!AddMethodInfoCache.TryAdd(objectType, addMethodInfo)) - { - ; - } + while (!AddMethodInfoCache.TryAdd(objectType, addMethodInfo)) { } } var toCloneEnumerable = (IEnumerable)obj; @@ -112,10 +109,7 @@ public class ReflectionsCloner(ISptLogger logger) : ICloner if (!MemberInfoCache.TryGetValue(objectType, out var memberInfos)) { memberInfos = objectType.GetMembers(BindingFlags.Public | BindingFlags.Instance); - while (!MemberInfoCache.TryAdd(objectType, memberInfos)) - { - ; - } + while (!MemberInfoCache.TryAdd(objectType, memberInfos)) { } } foreach (var member in memberInfos) @@ -181,19 +175,13 @@ public class ReflectionsCloner(ISptLogger logger) : ICloner if (!_itemPropertyInfoCache.TryGetValue(type, out var item)) { item = objectType.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance); - while (!_itemPropertyInfoCache.TryAdd(type, item)) - { - ; - } + while (!_itemPropertyInfoCache.TryAdd(type, item)) { } } if (!_listPropertyInfoCache.TryGetValue(type, out var list)) { list = objectType.GetProperty("List", BindingFlags.Public | BindingFlags.Instance); - while (!_listPropertyInfoCache.TryAdd(type, list)) - { - ; - } + while (!_listPropertyInfoCache.TryAdd(type, list)) { } } item.GetSetMethod(true) diff --git a/Libraries/SPTarkov.Server.Core/Utils/DatabaseImporter.cs b/Libraries/SPTarkov.Server.Core/Utils/DatabaseImporter.cs index 2de81df4..0d84c1af 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/DatabaseImporter.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/DatabaseImporter.cs @@ -3,8 +3,6 @@ using System.Security.Cryptography; using System.Text; using SPTarkov.DI.Annotations; using SPTarkov.Server.Core.DI; -using SPTarkov.Server.Core.Models.Common; -using SPTarkov.Server.Core.Models.Eft.Common.Tables; using SPTarkov.Server.Core.Models.Spt.Server; using SPTarkov.Server.Core.Models.Utils; using SPTarkov.Server.Core.Routers; @@ -25,8 +23,7 @@ public class DatabaseImporter( ) : IOnLoad { private const string _sptDataPath = "./SPT_Data/"; - protected ISptLogger _logger = logger; - protected Dictionary databaseHashes = []; + protected readonly Dictionary databaseHashes = []; public async Task OnLoad() { @@ -101,14 +98,14 @@ public class DatabaseImporter( } else { - _logger.Error( + logger.Error( _serverLocalisationService.GetText("validation_error_exception", checksFilePath) ); } } catch (Exception) { - _logger.Error( + logger.Error( _serverLocalisationService.GetText("validation_error_exception", checksFilePath) ); } @@ -120,7 +117,7 @@ public class DatabaseImporter( */ protected async Task HydrateDatabase(string filePath) { - _logger.Info(_serverLocalisationService.GetText("importing_database")); + logger.Info(_serverLocalisationService.GetText("importing_database")); Stopwatch timer = new(); timer.Start(); @@ -131,8 +128,8 @@ public class DatabaseImporter( timer.Stop(); - _logger.Info(_serverLocalisationService.GetText("importing_database_finish")); - _logger.Debug($"Database import took {timer.ElapsedMilliseconds}ms"); + logger.Info(_serverLocalisationService.GetText("importing_database_finish")); + logger.Debug($"Database import took {timer.ElapsedMilliseconds}ms"); _databaseServer.SetTables(dataToImport); } @@ -161,14 +158,14 @@ public class DatabaseImporter( { if (databaseHashes[relativePath] != hashString) { - _logger.Warning( + logger.Warning( _serverLocalisationService.GetText("validation_error_file", fileName) ); } } else { - _logger.Warning( + logger.Warning( _serverLocalisationService.GetText("validation_error_file", fileName) ); } diff --git a/Libraries/SPTarkov.Server.Core/Utils/HttpFileUtil.cs b/Libraries/SPTarkov.Server.Core/Utils/HttpFileUtil.cs index f0aaa54f..7c9d5639 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/HttpFileUtil.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/HttpFileUtil.cs @@ -6,14 +6,12 @@ namespace SPTarkov.Server.Core.Utils; [Injectable] public class HttpFileUtil(HttpServerHelper httpServerHelper) { - protected HttpServerHelper _httpServerHelper = httpServerHelper; - public async Task SendFile(HttpResponse resp, string filePath) { var pathSlice = filePath.Split("/"); - var mimePath = _httpServerHelper.GetMimeText(pathSlice[^1].Split(".")[^1]); + var mimePath = httpServerHelper.GetMimeText(pathSlice[^1].Split(".")[^1]); var type = string.IsNullOrWhiteSpace(mimePath) - ? _httpServerHelper.GetMimeText("txt") + ? httpServerHelper.GetMimeText("txt") : mimePath; resp.Headers.Append("Content-Type", type); await resp.SendFileAsync(filePath, CancellationToken.None); diff --git a/Libraries/SPTarkov.Server.Core/Utils/ImporterUtil.cs b/Libraries/SPTarkov.Server.Core/Utils/ImporterUtil.cs index 70ee7f74..e9afca5c 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/ImporterUtil.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/ImporterUtil.cs @@ -150,7 +150,7 @@ public class ImporterUtil(ISptLogger _logger, FileUtil _fileUtil, result, isDictionary ? [_fileUtil.StripExtension(file), fileDeserialized] - : new[] { fileDeserialized } + : [fileDeserialized] ); } } @@ -215,10 +215,7 @@ public class ImporterUtil(ISptLogger _logger, FileUtil _fileUtil, lock (dictionaryLock) { - setMethod.Invoke( - result, - isDictionary ? [directory, loadedData] : new[] { loadedData } - ); + setMethod.Invoke(result, isDictionary ? [directory, loadedData] : [loadedData]); } } } diff --git a/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/BaseInteractionRequestDataConverter.cs b/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/BaseInteractionRequestDataConverter.cs index 0ca5136a..1855c0f6 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/BaseInteractionRequestDataConverter.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Json/Converters/BaseInteractionRequestDataConverter.cs @@ -18,7 +18,10 @@ namespace SPTarkov.Server.Core.Utils.Json.Converters; public class BaseInteractionRequestDataConverter : JsonConverter { - private static Dictionary> _modHandlers = []; + private static readonly Dictionary< + string, + Func + > _modHandlers = []; public override BaseInteractionRequestData? Read( ref Utf8JsonReader reader, @@ -43,6 +46,7 @@ public class BaseInteractionRequestDataConverter : JsonConvertere.g. "Eat" /// Root json element of client request /// Raw JSON request text + /// Json parsing options /// BaseInteractionRequestData private static BaseInteractionRequestData? ConvertToCorrectType( string action, diff --git a/Libraries/SPTarkov.Server.Core/Utils/JsonUtil.cs b/Libraries/SPTarkov.Server.Core/Utils/JsonUtil.cs index ca9871f5..b216145b 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/JsonUtil.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/JsonUtil.cs @@ -173,7 +173,7 @@ public class JsonUtil /// /// Convert JSON into an object from a MemoryStream asynchronously /// - /// The memory stream to deserialize + /// The memory stream to deserialize /// T public async Task DeserializeFromMemoryStreamAsync(MemoryStream ms) { diff --git a/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/ConsoleLogHandler.cs b/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/ConsoleLogHandler.cs index 91e9ecd3..90786613 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/ConsoleLogHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/ConsoleLogHandler.cs @@ -6,7 +6,10 @@ namespace SPTarkov.Server.Core.Utils.Logger.Handlers; [Injectable(InjectionType.Singleton)] public class ConsoleLogHandler : BaseLogHandler { - public override LoggerType LoggerType => LoggerType.Console; + public override LoggerType LoggerType + { + get { return LoggerType.Console; } + } public override void Log(SptLogMessage message, BaseSptLoggerReference reference) { diff --git a/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/FileLogHandler.cs b/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/FileLogHandler.cs index 00d65ef3..0d3716ac 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/FileLogHandler.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Logger/Handlers/FileLogHandler.cs @@ -28,7 +28,10 @@ public class FileLogHandler(IEnumerable replacers) : BaseL private readonly ConcurrentDictionary _fileLocks = new(); private readonly ConcurrentDictionary _fileInfos = new(); private readonly ConcurrentDictionary _fileConfigs = new(); - public override LoggerType LoggerType => LoggerType.File; + public override LoggerType LoggerType + { + get { return LoggerType.File; } + } public override void Log(SptLogMessage message, BaseSptLoggerReference reference) { diff --git a/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLogger.cs b/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLogger.cs index d964d43a..5714b94f 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLogger.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLogger.cs @@ -25,14 +25,11 @@ public class SptLogger : ISptLogger, IDisposable _category = typeof(T).FullName; _loggerQueueManager = loggerQueueManager; - if (ProgramStatics.DEBUG()) - { - LoadConfig(fileUtil, jsonUtil, ConfigurationPathDev); - } - else - { - LoadConfig(fileUtil, jsonUtil, ConfigurationPath); - } + LoadConfig( + fileUtil, + jsonUtil, + ProgramStatics.DEBUG() ? ConfigurationPathDev : ConfigurationPath + ); if (_config == null) { diff --git a/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerConfiguration.cs b/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerConfiguration.cs index 098e1aab..9f2e3649 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerConfiguration.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerConfiguration.cs @@ -88,8 +88,8 @@ public class FileSptLoggerReference : BaseSptLoggerReference [JsonPropertyName("maxFileSizeMB")] public int MaxFileSizeMb { - get => _maxFileSizeMb; - set + get { return _maxFileSizeMb; } + init { if (value < 0) { @@ -104,8 +104,8 @@ public class FileSptLoggerReference : BaseSptLoggerReference [JsonPropertyName("maxRollingFiles")] public int MaxRollingFiles { - get => _maxRollingFiles; - set + get { return _maxRollingFiles; } + init { if (value < 0) { @@ -138,7 +138,7 @@ public enum SptLoggerFilterType public static class SptLoggerFilterExtensions { - private static ConcurrentDictionary _cachedRegexes = new(); + private static readonly ConcurrentDictionary _cachedRegexes = new(); public static bool Match(this SptLoggerFilter filter, SptLogMessage message) { diff --git a/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerQueueManager.cs b/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerQueueManager.cs index 0865b0cb..7e111abd 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerQueueManager.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Logger/SptLoggerQueueManager.cs @@ -20,17 +20,13 @@ public class SptLoggerQueueManager(IEnumerable logHandlers) { _config = config; - if (_logHandlers == null) - { - _logHandlers = logHandlers.ToDictionary(lh => lh.LoggerType, lh => lh); - } + _logHandlers ??= logHandlers.ToDictionary(lh => lh.LoggerType, lh => lh); lock (LoggerTaskLock) { if (_loggerTask == null) { - _loggerTask = new Thread(LoggerWorkerThread); - _loggerTask.IsBackground = true; + _loggerTask = new Thread(LoggerWorkerThread) { IsBackground = true }; _loggerTask.Start(); } } diff --git a/Libraries/SPTarkov.Server.Core/Utils/Watermark.cs b/Libraries/SPTarkov.Server.Core/Utils/Watermark.cs index ac0b1a33..228deee8 100644 --- a/Libraries/SPTarkov.Server.Core/Utils/Watermark.cs +++ b/Libraries/SPTarkov.Server.Core/Utils/Watermark.cs @@ -65,14 +65,14 @@ public class WatermarkLocale [Injectable(TypePriority = OnLoadOrder.Watermark)] public class Watermark : IOnLoad { - protected ConfigServer _configServer; - protected ServerLocalisationService _serverLocalisationService; + protected readonly ConfigServer _configServer; + protected readonly ServerLocalisationService _serverLocalisationService; - protected ISptLogger _logger; - protected WatermarkLocale _watermarkLocale; - protected CoreConfig sptConfig; - protected List text = []; - protected string versionLabel = ""; + protected readonly ISptLogger _logger; + protected readonly WatermarkLocale _watermarkLocale; + protected readonly CoreConfig sptConfig; + protected readonly List text = []; + protected string versionLabel = string.Empty; public Watermark( ISptLogger logger, @@ -97,8 +97,8 @@ public class Watermark : IOnLoad versionLabel = $"{sptConfig.ProjectName} {versionTag} {sptConfig.CompatibleTarkovVersion}"; - text = [versionLabel]; - text = [.. text, .. description]; + text.Add(versionLabel); + text.AddRange(description); if (ProgramStatics.DEBUG()) { @@ -213,9 +213,9 @@ public class Watermark : IOnLoad result.Add($"└─{line}─┘"); // Log watermark to screen - foreach (var text in result) + foreach (var resultText in result) { - _logger.LogWithColor(text, color); + _logger.LogWithColor(resultText, color); } } } diff --git a/SPTarkov.Server/Logger/SptLoggerProvider.cs b/SPTarkov.Server/Logger/SptLoggerProvider.cs index a89d8bce..7cdcbfe6 100644 --- a/SPTarkov.Server/Logger/SptLoggerProvider.cs +++ b/SPTarkov.Server/Logger/SptLoggerProvider.cs @@ -11,7 +11,7 @@ public class SptLoggerProvider( SptLoggerQueueManager queueManager ) : ILoggerProvider, ILoggerFactory { - private List loggerProviders = new(); + private readonly List loggerProviders = []; public void Dispose() { } diff --git a/SPTarkov.Server/Modding/ModLoadOrder.cs b/SPTarkov.Server/Modding/ModLoadOrder.cs index 44e70912..2916f2d2 100644 --- a/SPTarkov.Server/Modding/ModLoadOrder.cs +++ b/SPTarkov.Server/Modding/ModLoadOrder.cs @@ -43,13 +43,11 @@ public class ModLoadOrder(ICloner cloner) public HashSet GetModsOnLoadBefore(string mod) { - if (!mods.ContainsKey(mod)) + if (!mods.TryGetValue(mod, out var config)) { throw new Exception($"The mod {mod} does not exist!"); } - var config = mods[mod]; - var loadBefore = new HashSet(config.LoadBefore); foreach (var loadBeforeMod in loadBefore) @@ -93,13 +91,11 @@ public class ModLoadOrder(ICloner cloner) } // Check dependencies - if (!modsAvailable.ContainsKey(mod)) + if (!modsAvailable.TryGetValue(mod, out var config)) { throw new Exception("modloader-error_parsing_mod_load_order"); } - var config = modsAvailable[mod]; - config.LoadAfter ??= []; config.ModDependencies ??= []; @@ -107,9 +103,9 @@ public class ModLoadOrder(ICloner cloner) foreach (var modAfter in config.LoadAfter) { - if (modsAvailable.ContainsKey(modAfter)) + if (modsAvailable.TryGetValue(modAfter, out var value)) { - if (modsAvailable[modAfter]?.LoadAfter?.Contains(mod) ?? false) + if (value?.LoadAfter?.Contains(mod) ?? false) { throw new Exception("modloader-load_order_conflict"); } diff --git a/SPTarkov.Server/Modding/ModValidator.cs b/SPTarkov.Server/Modding/ModValidator.cs index 39095e23..83c8f0c8 100644 --- a/SPTarkov.Server/Modding/ModValidator.cs +++ b/SPTarkov.Server/Modding/ModValidator.cs @@ -21,11 +21,11 @@ public class ModValidator( { protected readonly string basepath = "user/mods/"; protected readonly string modOrderPath = "user/mods/order.json"; - protected Dictionary imported = []; - protected Dictionary order = []; - protected HashSet skippedMods = []; + protected readonly Dictionary imported = []; + protected readonly Dictionary order = []; + protected readonly HashSet skippedMods = []; - protected CoreConfig sptConfig = configServer.GetConfig(); + protected readonly CoreConfig sptConfig = configServer.GetConfig(); public List ValidateAndSort(List mods) { @@ -189,7 +189,7 @@ public class ModValidator( groupedMods.Add(name, [.. groupedMods.GetValueOrDefault(name) ?? [], mod]); // if there's more than one entry for a given mod it means there's at least 2 mods with the same author and name trying to load. - if (groupedMods[name].Count > 1 && !skippedMods.Contains(name)) + if (groupedMods[name].Count > 1) { skippedMods.Add(name); } diff --git a/Tools/HideoutCraftQuestIdGenerator/HideoutCraftQuestIdGenerator.cs b/Tools/HideoutCraftQuestIdGenerator/HideoutCraftQuestIdGenerator.cs index a45aaefa..115db649 100644 --- a/Tools/HideoutCraftQuestIdGenerator/HideoutCraftQuestIdGenerator.cs +++ b/Tools/HideoutCraftQuestIdGenerator/HideoutCraftQuestIdGenerator.cs @@ -58,7 +58,7 @@ public class HideoutCraftQuestIdGenerator( _databaseServer.GetTables().Hideout.Production, true ); - _fileUtil.WriteFile(productionFilePath, updatedProductionJson); + await _fileUtil.WriteFileAsync(productionFilePath, updatedProductionJson); } // Build a list of all quests and what production they unlock diff --git a/Tools/ItemTplGenerator/ItemTplGenerator.cs b/Tools/ItemTplGenerator/ItemTplGenerator.cs index ea84a933..e7677ace 100644 --- a/Tools/ItemTplGenerator/ItemTplGenerator.cs +++ b/Tools/ItemTplGenerator/ItemTplGenerator.cs @@ -161,16 +161,16 @@ public class ItemTplGenerator( itemKey = SanitizeEnumKey($"{itemKey}_{itemNameSuffix}"); // If we still collide, log an error - if (itemsObject.ContainsKey(itemKey)) + if (itemsObject.TryGetValue(itemKey, out var value)) { _logger.Error( - $"After rename, itemsObject already contains {itemKey} {itemsObject[itemKey]} => {item.Id}" + $"After rename, itemsObject already contains {itemKey} {value} => {item.Id}" ); } } else { - var val = itemsObject.ContainsKey(itemKey) ? itemsObject[itemKey] : itemKey; + var val = itemsObject.TryGetValue(itemKey, out var value) ? value : itemKey; _logger.Error( $"New itemOverride entry required: itemsObject already contains {itemKey} {val} => {item.Id}" ); @@ -444,9 +444,9 @@ public class ItemTplGenerator( var localeDb = _localeService.GetLocaleDb(); // Manual item name overrides - if (_itemOverrides.ContainsKey(item.Id)) + if (_itemOverrides.TryGetValue(item.Id, out var itemNameOverride)) { - itemName = _itemOverrides[item.Id].ToUpper(); + itemName = itemNameOverride.ToUpper(); } // For the listed types, user the item's _name property else if ( diff --git a/UnitTests/Tests/Extensions/ContainerExtensionsTests.cs b/UnitTests/Tests/Extensions/ContainerExtensionsTests.cs index 97707962..bd1de9ef 100644 --- a/UnitTests/Tests/Extensions/ContainerExtensionsTests.cs +++ b/UnitTests/Tests/Extensions/ContainerExtensionsTests.cs @@ -145,9 +145,9 @@ public partial class ContainerExtensionsTests [TestMethod] public void FindSlotForItem_1x2_item_fits_3x3_container_rotated_with_items() { - /// |1|1|1| - /// |1|0|0| - /// |1|1|1| + // |1|1|1| + // |1|0|0| + // |1|1|1| var container = new int[3, 3]; container[0, 0] = 1; container[0, 1] = 1; diff --git a/UnitTests/Tests/Test.cs b/UnitTests/Tests/Test.cs index 1360caea..51063fce 100644 --- a/UnitTests/Tests/Test.cs +++ b/UnitTests/Tests/Test.cs @@ -1,6 +1,5 @@ using SPTarkov.Server.Core.Models.Spt.Templates; using SPTarkov.Server.Core.Utils; -using SPTarkov.Server.Core.Utils.Json.Converters; using UnitTests.Mock; namespace UnitTests.Tests;