namespace Jellyfin.Plugin.YandexMusic.Providers; /// /// Reads the original embedded tags directly from the file, so matching is not affected by /// metadata previously written into Jellyfin's database. /// public static class AudioTagReader { /// Embedded tag values relevant for matching. public sealed record Tags( string? Title, string[] Artists, string[] AlbumArtists, string? Album, int? Year, string[] Genres, int? Track); /// Reads tags from a media file. Returns null when the file cannot be read. public static Tags? Read(string? path) { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) { return null; } try { using var file = TagLib.File.Create(path); var tag = file.Tag; var artists = (tag.Performers ?? []) .Where(a => !string.IsNullOrWhiteSpace(a)) .Select(a => a.Trim()) .ToArray(); var albumArtists = (tag.AlbumArtists ?? []) .Where(a => !string.IsNullOrWhiteSpace(a)) .Select(a => a.Trim()) .ToArray(); return new Tags( NullIfEmpty(tag.Title), artists, albumArtists, NullIfEmpty(tag.Album), tag.Year == 0 ? null : (int)tag.Year, (tag.Genres ?? []).Where(g => !string.IsNullOrWhiteSpace(g)).ToArray(), tag.Track == 0 ? null : (int)tag.Track); } catch (Exception) { return null; } } /// Parses "Artist - Title" from a file name when tags are missing. public static (string? Artist, string? Title) ParseFileName(string? path) { if (string.IsNullOrWhiteSpace(path)) { return (null, null); } var name = Path.GetFileNameWithoutExtension(path); var index = name.LastIndexOf(" - ", StringComparison.Ordinal); if (index <= 0 || index + 3 >= name.Length) { return (null, name); } return (name[..index].Trim(), name[(index + 3)..].Trim()); } private static string? NullIfEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); }