using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using Moonlight.Api.Configuration; using Moonlight.Api.Constants; using Moonlight.Api.Database; using Moonlight.Api.Database.Entities; using Moonlight.Api.Models; namespace Moonlight.Api.Services; public class FrontendService { private readonly IMemoryCache Cache; private readonly DatabaseRepository ThemeRepository; private readonly IOptions Options; private readonly SettingsService SettingsService; private const string CacheKey = $"Moonlight.{nameof(FrontendService)}.{nameof(GetConfigurationAsync)}"; public FrontendService(IMemoryCache cache, DatabaseRepository themeRepository, IOptions options, SettingsService settingsService) { Cache = cache; ThemeRepository = themeRepository; Options = options; SettingsService = settingsService; } public async Task GetConfigurationAsync() { if (Cache.TryGetValue(CacheKey, out FrontendConfiguration? value)) { if (value != null) return value; } var theme = await ThemeRepository .Query() .FirstOrDefaultAsync(x => x.IsEnabled); var name = await SettingsService.GetValueAsync(FrontendSettingConstants.Name); var config = new FrontendConfiguration(name ?? "Moonlight", theme?.CssContent); Cache.Set(CacheKey, config, TimeSpan.FromMinutes(Options.Value.CacheMinutes)); return config; } public Task ResetCacheAsync() { Cache.Remove(CacheKey); return Task.CompletedTask; } }