jellyfin-smart-playlist/Jellyfin.Plugin.SmartPlaylist/Store.cs
2024-12-21 01:09:41 +01:00

63 lines
2.9 KiB
C#

using YamlDotNet.Serialization;
namespace Jellyfin.Plugin.SmartPlaylist {
public interface IStore {
Task<SmartPlaylistDto> GetSmartPlaylistAsync(SmartPlaylistId smartPlaylistId);
Task<SmartPlaylistDto[]> GetAllSmartPlaylistsAsync();
Task SaveSmartPlaylistAsync(SmartPlaylistDto smartPlaylist);
void DeleteSmartPlaylistById(SmartPlaylistId smartPlaylistId);
void DeleteSmartPlaylist(SmartPlaylistDto smartPlaylist);
}
public class Store : IStore {
private readonly ISmartPlaylistFileSystem _fileSystem;
public Store(ISmartPlaylistFileSystem fileSystem) {
_fileSystem = fileSystem;
}
private async Task<SmartPlaylistDto> LoadPlaylistAsync(string filename) {
var r = await File.ReadAllTextAsync(filename);
if (r.Equals("")) {
r = "{}";
}
var dto = new DeserializerBuilder().Build().Deserialize<SmartPlaylistDto>(r);
if (dto == null)
{
throw new ApplicationException("");
}
if (dto.Id != Path.GetFileNameWithoutExtension(filename)) {
dto.Id = Path.GetFileNameWithoutExtension(filename);
}
if (dto.Name != Path.GetFileNameWithoutExtension(filename)) {
dto.Name = Path.GetFileNameWithoutExtension(filename);
}
if (dto.Filename != filename) {
dto.Filename = filename;
}
return dto;
}
public async Task<SmartPlaylistDto> GetSmartPlaylistAsync(SmartPlaylistId smartPlaylistId) {
string filename = _fileSystem.FindSmartPlaylistFilePath(smartPlaylistId);
return await LoadPlaylistAsync(filename).ConfigureAwait(false);
}
public async Task<SmartPlaylistDto[]> 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);
var text = new SerializerBuilder().Build().Serialize(smartPlaylist);
await File.WriteAllTextAsync(filename, text);
}
public 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);
}
}
}