From c36543bd1321cbb0e1486bde30c443920bcc4e56 Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 1 Apr 2025 12:33:03 +0100 Subject: [PATCH] Added ProfileDataService --- .../Services/Mod/ProfileDataService.cs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Libraries/SPTarkov.Server.Core/Services/Mod/ProfileDataService.cs diff --git a/Libraries/SPTarkov.Server.Core/Services/Mod/ProfileDataService.cs b/Libraries/SPTarkov.Server.Core/Services/Mod/ProfileDataService.cs new file mode 100644 index 00000000..5cb74485 --- /dev/null +++ b/Libraries/SPTarkov.Server.Core/Services/Mod/ProfileDataService.cs @@ -0,0 +1,54 @@ +using System.Collections.Concurrent; +using SPTarkov.Common.Annotations; +using SPTarkov.Server.Core.Models.Utils; +using SPTarkov.Server.Core.Utils; + +namespace SPTarkov.Server.Core.Services.Mod; + +[Injectable(InjectionType.Singleton)] +public class ProfileDataService(ISptLogger logger, FileUtil fileUtil, JsonUtil jsonUtil) +{ + protected const string ProfileDataFilepath = "user/profileData/"; + private readonly ConcurrentDictionary _profileDataCache = new(); + + public bool ProfileDataExists(string profileId, string modKey) + { + return fileUtil.FileExists($"{ProfileDataFilepath}{profileId}/{modKey}.json"); + } + + public T? GetProfileData(string profileId, string modKey) + { + var profileDataKey = $"{profileId}:{modKey}"; + if (!_profileDataCache.TryGetValue(profileDataKey, out var value)) + { + if (fileUtil.FileExists($"{ProfileDataFilepath}{profileId}/{modKey}.json")) + { + value = jsonUtil.Deserialize(fileUtil.ReadFile($"{ProfileDataFilepath}{profileId}/{modKey}.json")); + if (value != null) + { + while (!_profileDataCache.TryAdd(profileDataKey, value)) { } + } + } + else + { + value = null; + } + } + return (T?) value; + } + + public void SaveProfileData(string profileId, string modKey, T profileData) + { + if (profileData == null) + { + throw new ArgumentNullException(nameof(profileData)); + } + var data = jsonUtil.Serialize(profileData, profileData.GetType()); + if (data == null) + { + throw new Exception("The profile data when serialized resulted in a null value"); + } + while(!_profileDataCache.TryAdd($"{profileId}:{modKey}", data)) { } + fileUtil.WriteFile($"{ProfileDataFilepath}{profileId}/{modKey}.json", data); + } +}