using System.Text.Json; namespace Jellyfin.Plugin.SmartPlaylist { public interface IStore { Task GetSmartPlaylistAsync(SmartPlaylistId smartPlaylistId); Task GetAllSmartPlaylistsAsync(); Task SaveSmartPlaylistAsync(SmartPlaylistDto smartPlaylist); void DeleteSmartPlaylist(SmartPlaylistDto smartPlaylist); } public class Store : IStore { private readonly ISmartPlaylistFileSystem _fileSystem; public Store(ISmartPlaylistFileSystem fileSystem) { _fileSystem = fileSystem; } private async Task LoadPlaylistAsync(string filename) { await using var r = File.OpenRead(filename); var dto = (await JsonSerializer.DeserializeAsync(r).ConfigureAwait(false)); dto.Fill(filename); return dto; } public async Task GetSmartPlaylistAsync(SmartPlaylistId smartPlaylistId) { string filename = _fileSystem.FindSmartPlaylistFilePath(smartPlaylistId); return await LoadPlaylistAsync(filename).ConfigureAwait(false); } public async Task GetAllSmartPlaylistsAsync() { var t = _fileSystem.FindAllSmartPlaylistFilePaths().Select(LoadPlaylistAsync).ToArray(); await Task.WhenAll(t).ConfigureAwait(false); return t.Where(x => x != null).Select(x => x.Result).ToArray(); } public async Task SaveSmartPlaylistAsync(SmartPlaylistDto smartPlaylist) { string filename = _fileSystem.GetSmartPlaylistFilePath(smartPlaylist.Id); await using var w = File.Create(filename); await JsonSerializer.SerializeAsync(w, smartPlaylist).ConfigureAwait(false); } private void DeleteSmartPlaylistById(SmartPlaylistId smartPlaylistId) { try { string filename = _fileSystem.FindSmartPlaylistFilePath(smartPlaylistId); if (File.Exists(filename)) { File.Delete(filename); } } catch (System.InvalidOperationException) {} } public void DeleteSmartPlaylist(SmartPlaylistDto smartPlaylist) { if (File.Exists(smartPlaylist.Filename)) { File.Delete(smartPlaylist.Filename); } DeleteSmartPlaylistById(smartPlaylist.Id); } } }