diff --git a/src/Core/Abstractions/ISettingsService.cs b/src/Core/Abstractions/ISettingsService.cs new file mode 100644 index 000000000..a5b780e8d --- /dev/null +++ b/src/Core/Abstractions/ISettingsService.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Bit.Core.Abstractions +{ + public interface ISettingsService + { + Task ClearAsync(string userId); + void ClearCache(); + Task>> GetEquivalentDomainsAsync(); + Task SetEquivalentDomainsAsync(List> equivalentDomains); + } +} \ No newline at end of file diff --git a/src/Core/Services/SettingsService.cs b/src/Core/Services/SettingsService.cs new file mode 100644 index 000000000..7f607c86f --- /dev/null +++ b/src/Core/Services/SettingsService.cs @@ -0,0 +1,90 @@ +using Bit.Core.Abstractions; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Bit.Core.Services +{ + public class SettingsService : ISettingsService + { + private const string Keys_SettingsFormat = "settings_{0}"; + private const string Keys_EquivalentDomains = "equivalentDomains"; + + private readonly IUserService _userService; + private readonly IStorageService _storageService; + + private Dictionary _settingsCache; + + public SettingsService( + IUserService userService, + IStorageService storageService) + { + _userService = userService; + _storageService = storageService; + } + + public void ClearCache() + { + _settingsCache.Clear(); + _settingsCache = null; + } + + public Task>> GetEquivalentDomainsAsync() + { + return GetSettingsKeyAsync>>(Keys_EquivalentDomains); + } + + public Task SetEquivalentDomainsAsync(List> equivalentDomains) + { + return SetSettingsKeyAsync(Keys_EquivalentDomains, equivalentDomains); + } + + public async Task ClearAsync(string userId) + { + await _storageService.RemoveAsync(string.Format(Keys_SettingsFormat, userId)); + ClearCache(); + } + + // Helpers + + private async Task> GetSettingsAsync() + { + if(_settingsCache == null) + { + var userId = await _userService.GetUserIdAsync(); + _settingsCache = await _storageService.GetAsync>( + string.Format(Keys_SettingsFormat, userId)); + } + return _settingsCache; + } + + private async Task GetSettingsKeyAsync(string key) + { + var settings = await GetSettingsAsync(); + if(settings != null && settings.ContainsKey(key)) + { + return (T)settings[key]; + } + return (T)(object)null; + } + + private async Task SetSettingsKeyAsync(string key, T value) + { + var userId = await _userService.GetUserIdAsync(); + var settings = await GetSettingsAsync(); + if(settings == null) + { + settings = new Dictionary(); + } + if(settings.ContainsKey(key)) + { + settings[key] = value; + } + else + { + settings.Add(key, value); + } + await _storageService.SaveAsync(string.Format(Keys_SettingsFormat, userId), settings); + _settingsCache = settings; + } + } +}