From 78e8c1b3c16cc52562a30d1c3f4de106901203ae Mon Sep 17 00:00:00 2001 From: Chomp Date: Tue, 28 Jan 2025 19:51:52 +0000 Subject: [PATCH] Implemented `BundleHashCacheService` --- .../Services/Cache/BundleHashCacheService.cs | 45 ++++++++++++++----- Libraries/Core/Utils/FileUtil.cs | 4 +- 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/Libraries/Core/Services/Cache/BundleHashCacheService.cs b/Libraries/Core/Services/Cache/BundleHashCacheService.cs index cac505af..c16829b5 100644 --- a/Libraries/Core/Services/Cache/BundleHashCacheService.cs +++ b/Libraries/Core/Services/Cache/BundleHashCacheService.cs @@ -1,29 +1,54 @@ -namespace Core.Services.Cache; +using Core.Models.Utils; +using Core.Utils; +using SptCommon.Annotations; -public class BundleHashCacheService +namespace Core.Services.Cache; + +[Injectable] +public class BundleHashCacheService( + ISptLogger _logger, + HashUtil _hashUtil, + JsonUtil _jsonUtil, + FileUtil _fileUtil + ) { - public int GetStoredValue(string key) + protected Dictionary _bundleHashes = new(); + protected readonly string _bundleHashCachePath = "./user/cache/bundleHashCache.json"; + + public string GetStoredValue(string key) { - throw new NotImplementedException(); + _bundleHashes.TryGetValue(key, out var value); + + return value; } - public void StoreValue(string key, int value) + public void StoreValue(string key, string value) { - throw new NotImplementedException(); + _bundleHashes.Add(key, value); + + _fileUtil.WriteFile(_bundleHashCachePath, _jsonUtil.Serialize(_bundleHashes)); + + _logger.Debug($"Bundle {key} hash stored in {_bundleHashCachePath}"); } - public bool MatchWithStoredHash(string bundlePath, int hash) + public bool MatchWithStoredHash(string bundlePath, string hash) { - throw new NotImplementedException(); + return GetStoredValue(bundlePath) == hash; } public bool CalculateAndMatchHash(string bundlePath) { - throw new NotImplementedException(); + var fileContents = _fileUtil.ReadFile(bundlePath); + var generatedHash = _hashUtil.GenerateCrc32ForData(fileContents); + + return MatchWithStoredHash(bundlePath, generatedHash); } public void CalculateAndStoreHash(string bundlePath) { - throw new NotImplementedException(); + var fileContents = _fileUtil.ReadFile(bundlePath); + var generatedHash = _hashUtil.GenerateCrc32ForData(fileContents); + + StoreValue(bundlePath, generatedHash); } } diff --git a/Libraries/Core/Utils/FileUtil.cs b/Libraries/Core/Utils/FileUtil.cs index 692dbc9b..ca53fb0a 100644 --- a/Libraries/Core/Utils/FileUtil.cs +++ b/Libraries/Core/Utils/FileUtil.cs @@ -62,11 +62,11 @@ public class FileUtil return reader.ReadToEnd(); } - public void WriteFile(string filePath, string jsonProfile) + public void WriteFile(string filePath, string json) { if (!FileExists(filePath)) CreateFile(filePath); - File.WriteAllText(filePath, jsonProfile); + File.WriteAllText(filePath, json); } private void CreateFile(string filePath)