commit c3dc9013379ef3956aa17adea89bcbfe403ad0f0 Author: opencode Date: Fri Nov 27 18:56:15 2026 +0300 Yandex Music metadata plugin for Jellyfin 12.4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f23bf3c --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +bin/ +obj/ +publish/ +artifacts/ +*.user +.DS_Store diff --git a/Jellyfin.Plugin.YandexMusic/Api/YandexMusicController.cs b/Jellyfin.Plugin.YandexMusic/Api/YandexMusicController.cs new file mode 100644 index 0000000..6c81bc8 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Api/YandexMusicController.cs @@ -0,0 +1,117 @@ +using System.Collections.Concurrent; +using Jellyfin.Plugin.YandexMusic.Yandex; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Plugin.YandexMusic.Api; + +/// +/// Plugin API used by the configuration page for Yandex OAuth device flow. +/// +[ApiController] +[Route("YandexMusic")] +[Authorize(Policy = "RequiresElevation")] +public class YandexMusicController : ControllerBase +{ + private static readonly ConcurrentDictionary Sessions = new(); + + private readonly YandexMusicClient _client; + + /// + /// Initializes a new instance of the class. + /// + public YandexMusicController(YandexMusicClient client) + { + _client = client; + } + + /// Starts the device flow. + [HttpPost("DeviceCode")] + public async Task> StartDeviceCode(CancellationToken cancellationToken) + { + var code = await _client.RequestDeviceCodeAsync(cancellationToken).ConfigureAwait(false); + if (code is null) + { + return StatusCode(502, new { error = "Yandex OAuth did not return a device code." }); + } + + Sessions[code.DeviceCode] = DateTimeOffset.UtcNow.AddSeconds(code.ExpiresIn); + return new DeviceCodeResult( + code.DeviceCode, + code.UserCode, + code.VerificationUrl, + code.ExpiresIn, + Math.Max(2, code.Interval)); + } + + /// Polls the device flow once. + [HttpPost("DeviceCode/Poll")] + public async Task> PollDeviceCode( + [FromBody] DevicePollRequest request, + CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.DeviceCode) + || !Sessions.TryGetValue(request.DeviceCode, out var expires) + || expires < DateTimeOffset.UtcNow) + { + return new DevicePollResult("expired", null, "Код истёк, запросите новый."); + } + + var token = await _client.PollDeviceTokenAsync(request.DeviceCode, cancellationToken).ConfigureAwait(false); + if (token is null) + { + return new DevicePollResult("pending", null, null); + } + + if (string.IsNullOrWhiteSpace(token.AccessToken)) + { + return new DevicePollResult("error", null, token.ErrorDescription ?? token.Error ?? "Не удалось получить токен."); + } + + var config = Plugin.Instance!.Configuration; + config.Token = token.AccessToken!; + Plugin.Instance.UpdateConfiguration(config); + Sessions.TryRemove(request.DeviceCode, out _); + + return new DevicePollResult("ok", token.AccessToken, null); + } + + /// Returns connection status. + [HttpGet("Status")] + public async Task> Status(CancellationToken cancellationToken) + { + var connected = await _client.TestConnectionAsync(cancellationToken).ConfigureAwait(false); + var config = Plugin.Instance?.Configuration; + return new StatusResult( + connected, + !string.IsNullOrWhiteSpace(config?.Token), + connected ? null : "api.music.yandex.net недоступен"); + } + + /// Clears the saved token. + [HttpPost("Logout")] + public ActionResult Logout() + { + var config = Plugin.Instance!.Configuration; + config.Token = string.Empty; + Plugin.Instance.UpdateConfiguration(config); + return NoContent(); + } +} + +/// Device code returned to the config page. +public record DeviceCodeResult( + string DeviceCode, + string UserCode, + string VerificationUrl, + int ExpiresIn, + int Interval); + +/// Device poll request. +public record DevicePollRequest(string DeviceCode); + +/// Device poll result. +public record DevicePollResult(string Status, string? Token, string? Error); + +/// Plugin status. +public record StatusResult(bool Connected, bool HasToken, string? Error); diff --git a/Jellyfin.Plugin.YandexMusic/Configuration/PluginConfiguration.cs b/Jellyfin.Plugin.YandexMusic/Configuration/PluginConfiguration.cs new file mode 100644 index 0000000..b60b338 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Configuration/PluginConfiguration.cs @@ -0,0 +1,75 @@ +using MediaBrowser.Model.Plugins; + +namespace Jellyfin.Plugin.YandexMusic.Configuration; + +/// +/// Plugin configuration. +/// +public class PluginConfiguration : BasePluginConfiguration +{ + /// + /// Gets or sets the Yandex OAuth token. Optional, required only for lyrics. + /// + public string Token { get; set; } = string.Empty; + + /// + /// Gets or sets the preferred language for genre names and artist descriptions. + /// + public string Language { get; set; } = "ru"; + + /// + /// Gets or sets a value indicating whether song metadata is enabled. + /// + public bool EnableSongMetadata { get; set; } = true; + + /// + /// Gets or sets a value indicating whether album metadata is enabled. + /// + public bool EnableAlbumMetadata { get; set; } = true; + + /// + /// Gets or sets a value indicating whether artist metadata is enabled. + /// + public bool EnableArtistMetadata { get; set; } = true; + + /// + /// Gets or sets a value indicating whether cover art is enabled. + /// + public bool EnableImages { get; set; } = true; + + /// + /// Gets or sets a value indicating whether lyrics are enabled. + /// + public bool EnableLyrics { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the real album title from Yandex is written to the track's Album field. + /// When disabled (default), the existing album tag is kept. + /// + public bool UseYandexAlbumName { get; set; } + + /// + /// Gets or sets a value indicating whether the original release year from Yandex may replace the year tag. + /// + public bool UseYandexYear { get; set; } = true; + + /// + /// Gets or sets the minimum match score (0..1) required to accept a search result. + /// + public double MatchThreshold { get; set; } = 0.72; + + /// + /// Gets or sets the duration tolerance in seconds used while matching tracks. + /// + public int DurationToleranceSeconds { get; set; } = 12; + + /// + /// Gets or sets a value indicating whether genres from Yandex are written to items. + /// + public bool EnableGenres { get; set; } = true; + + /// + /// Gets or sets a value indicating whether labels are written as studios. + /// + public bool EnableLabels { get; set; } = true; +} diff --git a/Jellyfin.Plugin.YandexMusic/Configuration/configPage.html b/Jellyfin.Plugin.YandexMusic/Configuration/configPage.html new file mode 100644 index 0000000..4701834 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Configuration/configPage.html @@ -0,0 +1,279 @@ + + + + + Yandex Music + + +
+
+
+
+
+

Подключение к Яндекс.Музыке

+
+ Метаданные, обложки и жанры доступны без авторизации. Токен нужен только для текстов песен. + Токен хранится в конфигурации плагина на сервере. +
+
+ + +
+
+ + + +
+ +
+
+ +
+

Что обогащать

+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+

Поведение

+
+ + +
+
+ +
+ Если включить, отдельные файлы с одинаковым альбомом соберутся в альбомы после обновления метаданных. +
+
+
+ +
+
+ + +
Чем выше, тем меньше ложных совпадений и больше пропусков.
+
+
+ + +
+
+ +
+ +
+
+
+
+ + +
+ + diff --git a/Jellyfin.Plugin.YandexMusic/Jellyfin.Plugin.YandexMusic.csproj b/Jellyfin.Plugin.YandexMusic/Jellyfin.Plugin.YandexMusic.csproj new file mode 100644 index 0000000..be385f8 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Jellyfin.Plugin.YandexMusic.csproj @@ -0,0 +1,32 @@ + + + + net10.0 + Jellyfin.Plugin.YandexMusic + Jellyfin.Plugin.YandexMusic + false + enable + enable + Default + $(NoWarn);CA1031;CA1848;CA2007;CA1305 + + + + + runtime + + + runtime + + + + + + + + + + + + + diff --git a/Jellyfin.Plugin.YandexMusic/Matching/TextMatch.cs b/Jellyfin.Plugin.YandexMusic/Matching/TextMatch.cs new file mode 100644 index 0000000..016e97b --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Matching/TextMatch.cs @@ -0,0 +1,297 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using Jellyfin.Plugin.YandexMusic.Yandex; + +namespace Jellyfin.Plugin.YandexMusic.Matching; + +/// +/// Text normalization and fuzzy matching helpers. +/// +public static partial class TextMatch +{ + /// Normalizes a title or artist name for comparison. + public static string Normalize(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return string.Empty; + } + + var text = value.ToLowerInvariant().Replace('ё', 'е'); + text = ParenthesesRegex().Replace(text, " "); + text = BracketsRegex().Replace(text, " "); + var featIndex = text.IndexOf(" feat", StringComparison.Ordinal); + if (featIndex > 0) + { + text = text[..featIndex]; + } + + var builder = new StringBuilder(text.Length); + var previousSpace = true; + foreach (var ch in text) + { + if (char.IsLetterOrDigit(ch)) + { + builder.Append(ch); + previousSpace = false; + } + else if (!previousSpace) + { + builder.Append(' '); + previousSpace = true; + } + } + + return builder.ToString().Trim(); + } + + /// Similarity in range 0..1 (best of edit distance ratio and token overlap). + public static double Similarity(string? left, string? right) + { + var a = Normalize(left); + var b = Normalize(right); + if (a.Length == 0 || b.Length == 0) + { + return 0; + } + + if (string.Equals(a, b, StringComparison.Ordinal)) + { + return 1; + } + + return Math.Max(LevenshteinRatio(a, b), TokenJaccard(a, b)); + } + + /// Best similarity between two artist lists. + public static double ArtistSimilarity(IEnumerable left, IEnumerable right) + { + var leftParts = left.SelectMany(SplitArtists).ToArray(); + var rightParts = right.SelectMany(SplitArtists).ToArray(); + var best = 0d; + foreach (var a in leftParts) + { + foreach (var b in rightParts) + { + best = Math.Max(best, Similarity(a, b)); + } + } + + return best; + } + + /// Splits a combined artist string ("A, B & C feat. D") into individual names. + public static IEnumerable SplitArtists(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + yield break; + } + + var text = value.Replace(" & ", ", ", StringComparison.Ordinal) + .Replace(" and ", ", ", StringComparison.OrdinalIgnoreCase) + .Replace(" feat. ", ", ", StringComparison.OrdinalIgnoreCase) + .Replace(" feat ", ", ", StringComparison.OrdinalIgnoreCase); + + foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (part.Length > 0) + { + yield return part; + } + } + } + + private static double LevenshteinRatio(string a, string b) + { + var distance = Levenshtein(a, b); + var max = Math.Max(a.Length, b.Length); + return max == 0 ? 1 : 1d - (double)distance / max; + } + + private static int Levenshtein(string a, string b) + { + if (a.Length == 0) + { + return b.Length; + } + + if (b.Length == 0) + { + return a.Length; + } + + var previous = new int[b.Length + 1]; + var current = new int[b.Length + 1]; + for (var j = 0; j <= b.Length; j++) + { + previous[j] = j; + } + + for (var i = 1; i <= a.Length; i++) + { + current[0] = i; + for (var j = 1; j <= b.Length; j++) + { + var cost = a[i - 1] == b[j - 1] ? 0 : 1; + current[j] = Math.Min( + Math.Min(current[j - 1] + 1, previous[j] + 1), + previous[j - 1] + cost); + } + + (previous, current) = (current, previous); + } + + return previous[b.Length]; + } + + private static double TokenJaccard(string a, string b) + { + var left = a.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var right = b.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (left.Length == 0 || right.Length == 0) + { + return 0; + } + + var common = left.Intersect(right, StringComparer.Ordinal).Count(); + var union = left.Union(right, StringComparer.Ordinal).Count(); + return union == 0 ? 0 : (double)common / union; + } + + [GeneratedRegex(@"\([^)]*\)", RegexOptions.CultureInvariant)] + private static partial Regex ParenthesesRegex(); + + [GeneratedRegex(@"\[[^\]]*\]", RegexOptions.CultureInvariant)] + private static partial Regex BracketsRegex(); +} + +/// +/// Scores Yandex search results against local tags. +/// +public static class MatchScoring +{ + /// Duration in milliseconds from Jellyfin ticks. + public static long TicksToMilliseconds(long? ticks) + => ticks is null ? 0 : ticks.Value / TimeSpan.TicksPerMillisecond; + + /// Finds the best matching track. + public static (TrackDto Track, double Score)? FindBestTrack( + IEnumerable tracks, + string? title, + IReadOnlyList artists, + long durationMs, + double threshold, + int toleranceSeconds) + { + (TrackDto Track, double Score)? best = null; + foreach (var track in tracks) + { + var titleScore = TextMatch.Similarity(title, track.Title); + var artistScore = TextMatch.ArtistSimilarity( + artists, + track.Artists.Select(a => a.Name)); + var durationScore = DurationScore(durationMs, track.DurationMs, toleranceSeconds); + + var score = durationScore is null + ? (0.6 * titleScore) + (0.4 * artistScore) + : (0.5 * titleScore) + (0.3 * artistScore) + (0.2 * durationScore.Value); + + if (titleScore < 0.68 || artistScore < 0.42) + { + continue; + } + + if (best is null || score > best.Value.Score) + { + best = (track, score); + } + } + + return best is not null && best.Value.Score >= threshold ? best : null; + } + + /// Finds the best matching album. + public static (AlbumDto Album, double Score)? FindBestAlbum( + IEnumerable albums, + string? title, + IReadOnlyList artists, + int? year, + double threshold) + { + (AlbumDto Album, double Score)? best = null; + foreach (var album in albums) + { + var titleScore = TextMatch.Similarity(title, album.Title); + var artistScore = artists.Count == 0 + ? 1 + : TextMatch.ArtistSimilarity(artists, album.Artists.Select(a => a.Name)); + var yearScore = year is null || album.Year is null ? 0.5 : (year == album.Year ? 1 : 0); + var score = (0.55 * titleScore) + (0.3 * artistScore) + (0.15 * yearScore); + + if (titleScore < 0.6) + { + continue; + } + + if (best is null || score > best.Value.Score) + { + best = (album, score); + } + } + + return best is not null && best.Value.Score >= threshold ? best : null; + } + + /// Finds an artist whose name matches exactly (or nearly exactly). + public static ArtistDto? FindBestArtist(IEnumerable artists, string? name) + { + var normalized = TextMatch.Normalize(name); + if (normalized.Length == 0) + { + return null; + } + + ArtistDto? best = null; + var bestScore = 0d; + foreach (var artist in artists) + { + var score = TextMatch.Similarity(normalized, artist.Name); + if (score > bestScore) + { + bestScore = score; + best = artist; + } + } + + return bestScore >= 0.86 ? best : null; + } + + private static double? DurationScore(long localMs, long? remoteMs, int toleranceSeconds) + { + if (localMs <= 0 || remoteMs is null or <= 0) + { + return null; + } + + var tolerance = Math.Max(2, toleranceSeconds) * 1000; + var difference = Math.Abs(localMs - remoteMs.Value); + if (difference <= tolerance / 2.0) + { + return 1; + } + + if (difference <= tolerance) + { + return 0.85; + } + + if (difference <= tolerance * 2.0) + { + return 0.45; + } + + return 0.0; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Plugin.cs b/Jellyfin.Plugin.YandexMusic/Plugin.cs new file mode 100644 index 0000000..d2a6aa4 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Plugin.cs @@ -0,0 +1,52 @@ +using System.Globalization; +using Jellyfin.Plugin.YandexMusic.Configuration; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace Jellyfin.Plugin.YandexMusic; + +/// +/// The Yandex Music metadata plugin. +/// +public class Plugin : BasePlugin, IHasWebPages +{ + /// + /// Initializes a new instance of the class. + /// + /// Application paths. + /// XML serializer. + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + } + + /// + public override string Name => "Yandex Music"; + + /// + public override Guid Id => Guid.Parse("f3b9626b-da14-4cbf-8ad1-33b92cfa6656"); + + /// + public override string Description => "Metadata, cover art and lyrics from Yandex Music."; + + /// + /// Gets the current plugin instance. + /// + public static Plugin? Instance { get; private set; } + + /// + public IEnumerable GetPages() + { + yield return new PluginPageInfo + { + Name = Name, + EmbeddedResourcePath = string.Format( + CultureInfo.InvariantCulture, + "{0}.Configuration.configPage.html", + GetType().Namespace) + }; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/PluginServiceRegistrator.cs b/Jellyfin.Plugin.YandexMusic/PluginServiceRegistrator.cs new file mode 100644 index 0000000..231be23 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/PluginServiceRegistrator.cs @@ -0,0 +1,18 @@ +using MediaBrowser.Controller; +using MediaBrowser.Controller.Plugins; +using Microsoft.Extensions.DependencyInjection; +using Jellyfin.Plugin.YandexMusic.Yandex; + +namespace Jellyfin.Plugin.YandexMusic; + +/// +/// Registers plugin services in the Jellyfin DI container. +/// +public class PluginServiceRegistrator : IPluginServiceRegistrator +{ + /// + public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost) + { + serviceCollection.AddSingleton(); + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/ImageResponseFactory.cs b/Jellyfin.Plugin.YandexMusic/Providers/ImageResponseFactory.cs new file mode 100644 index 0000000..91a1208 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/ImageResponseFactory.cs @@ -0,0 +1,26 @@ +using System.Net; +using System.Net.Http.Headers; +using Jellyfin.Plugin.YandexMusic.Yandex; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// Creates image responses for search results. +internal static class ImageResponseFactory +{ + /// Downloads an image and wraps it into an HTTP response. + public static async Task FromUrlAsync( + YandexMusicClient client, + string url, + CancellationToken cancellationToken) + { + var bytes = await client.GetImageBytesAsync(url, cancellationToken).ConfigureAwait(false); + if (bytes is null) + { + return new HttpResponseMessage(HttpStatusCode.NotFound); + } + + var content = new ByteArrayContent(bytes); + content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/Mapping.cs b/Jellyfin.Plugin.YandexMusic/Providers/Mapping.cs new file mode 100644 index 0000000..b7e48bc --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/Mapping.cs @@ -0,0 +1,151 @@ +using System.Globalization; +using Jellyfin.Plugin.YandexMusic.Configuration; +using Jellyfin.Plugin.YandexMusic.Yandex; +using MediaBrowser.Model.Entities; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// Provider id keys used by this plugin. +public static class YandexProviderIds +{ + /// Track id. + public const string Track = "YandexMusicTrack"; + + /// Album id. + public const string Album = "YandexMusicAlbum"; + + /// Artist id. + public const string Artist = "YandexMusicArtist"; +} + +/// Shared mapping helpers. +public static class Mapping +{ + /// Provider display name. + public const string ProviderName = "Yandex Music"; + + private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration(); + + /// Gets a provider id from lookup info. + public static long? GetId(IReadOnlyDictionary? ids, string key) + { + if (ids is null || !ids.TryGetValue(key, out var value) || string.IsNullOrWhiteSpace(value)) + { + return null; + } + + return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) ? id : null; + } + + /// Gets a provider id from an item. + public static long? GetId(MediaBrowser.Controller.Entities.BaseItem item, string key) + { + var value = item.GetProviderId(key); + return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) ? id : null; + } + + /// Parses a Yandex release date. + public static DateTime? ParseReleaseDate(string? releaseDate) + { + if (string.IsNullOrWhiteSpace(releaseDate)) + { + return null; + } + + if (DateTime.TryParse(releaseDate, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var parsed)) + { + return parsed.Year is >= 1900 and <= 2100 ? parsed : null; + } + + return null; + } + + /// Validates a release year. + public static int? ValidYear(int? year) + => year is >= 1900 and <= 2100 ? year : null; + + /// Maps a Yandex album genre to a Jellyfin genre name. + public static async Task GenresAsync( + YandexMusicClient client, + string? albumGenre, + IEnumerable? artistGenres, + CancellationToken cancellationToken) + { + if (!Config.EnableGenres) + { + return []; + } + + var result = new List(); + var name = await client.GetGenreNameAsync(albumGenre, cancellationToken).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(name)) + { + result.Add(name); + } + + foreach (var genre in (artistGenres ?? []).Take(4)) + { + var artistGenre = await client.GetGenreNameAsync(genre, cancellationToken).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(artistGenre) + && !result.Contains(artistGenre, StringComparer.OrdinalIgnoreCase)) + { + result.Add(artistGenre); + } + } + + return result.ToArray(); + } + + /// Gets label names. + public static string[] Labels(AlbumDto? album) + { + if (album is null || !Config.EnableLabels) + { + return []; + } + + return album.Labels + .Select(l => l.Name) + .Where(n => !string.IsNullOrWhiteSpace(n)) + .Select(n => n!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + } + + /// Adds a primary remote image when allowed. + public static void AddPrimaryImage( + MediaBrowser.Controller.Providers.MetadataResult result, + string? coverUri, + int size = 1000) + { + if (!Config.EnableImages) + { + return; + } + + var url = YandexMusicClient.BuildCoverUrl(coverUri, size); + if (!string.IsNullOrWhiteSpace(url)) + { + result.RemoteImages.Add((url, MediaBrowser.Model.Entities.ImageType.Primary)); + } + } + + /// Adds a remote image of a given type. + public static void AddImage( + MediaBrowser.Controller.Providers.MetadataResult result, + string? coverUri, + MediaBrowser.Model.Entities.ImageType type, + int size = 1000) + { + if (!Config.EnableImages) + { + return; + } + + var url = YandexMusicClient.BuildCoverUrl(coverUri, size); + if (!string.IsNullOrWhiteSpace(url)) + { + result.RemoteImages.Add((url, type)); + } + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicAlbumProvider.cs b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicAlbumProvider.cs new file mode 100644 index 0000000..b99a114 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicAlbumProvider.cs @@ -0,0 +1,173 @@ +using System.Globalization; +using Jellyfin.Plugin.YandexMusic.Configuration; +using Jellyfin.Plugin.YandexMusic.Matching; +using Jellyfin.Plugin.YandexMusic.Yandex; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// +/// Metadata provider for music albums. +/// +public class YandexMusicAlbumProvider : IRemoteMetadataProvider, IHasOrder +{ + private readonly YandexMusicClient _client; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public YandexMusicAlbumProvider(YandexMusicClient client, ILogger logger) + { + _client = client; + _logger = logger; + } + + /// + public string Name => Mapping.ProviderName; + + /// + public int Order => 1; + + /// + public async Task> GetMetadata(AlbumInfo info, CancellationToken cancellationToken) + { + var result = new MetadataResult { Item = new MusicAlbum() }; + var config = Plugin.Instance?.Configuration ?? new PluginConfiguration(); + if (!config.EnableAlbumMetadata) + { + return result; + } + + try + { + var album = await ResolveAlbumAsync(info, config, cancellationToken).ConfigureAwait(false); + if (album is null) + { + return result; + } + + var artists = album.Artists + .Select(a => a.Name) + .Where(n => !string.IsNullOrWhiteSpace(n)) + .Select(n => n!) + .ToArray(); + if (artists.Length == 0) + { + artists = info.AlbumArtists.ToArray(); + } + + var item = result.Item; + if (!string.IsNullOrWhiteSpace(album.Title)) + { + item.Name = album.Title!; + } + + item.Artists = artists; + item.AlbumArtists = artists; + item.ProductionYear = Mapping.ValidYear(album.Year) ?? info.Year; + item.PremiereDate = Mapping.ParseReleaseDate(album.ReleaseDate); + item.Genres = await Mapping.GenresAsync(_client, album.Genre, null, cancellationToken) + .ConfigureAwait(false); + + var labels = Mapping.Labels(album); + if (labels.Length > 0) + { + item.Studios = labels; + } + + item.SetProviderId(YandexProviderIds.Album, album.Id.ToString(CultureInfo.InvariantCulture)); + var primaryArtist = album.Artists.FirstOrDefault(a => a.Id > 0); + if (primaryArtist is not null) + { + item.SetProviderId(YandexProviderIds.Artist, primaryArtist.Id.ToString(CultureInfo.InvariantCulture)); + } + + Mapping.AddPrimaryImage(result, album.CoverUri ?? album.OgImage, 1200); + result.HasMetadata = true; + result.QueriedById = Mapping.GetId(info.ProviderIds, YandexProviderIds.Album) is not null; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Yandex Music failed to provide album metadata for {Name}", info.Name); + } + + return result; + } + + /// + public async Task> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken) + { + var results = new List(); + try + { + var albums = await SearchAlbumsAsync(searchInfo, cancellationToken).ConfigureAwait(false); + foreach (var album in albums) + { + results.Add(new RemoteSearchResult + { + Name = album.Title, + ProductionYear = album.Year, + Artists = album.Artists + .Select(a => new RemoteSearchResult { Name = a.Name }) + .ToArray(), + ImageUrl = YandexMusicClient.BuildCoverUrl(album.CoverUri, 300), + ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [YandexProviderIds.Album] = album.Id.ToString(CultureInfo.InvariantCulture) + }, + SearchProviderName = Name + }); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Yandex Music album search failed for {Name}", searchInfo.Name); + } + + return results; + } + + /// + public Task GetImageResponse(string url, CancellationToken cancellationToken) + => ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken); + + private async Task ResolveAlbumAsync(AlbumInfo info, PluginConfiguration config, CancellationToken cancellationToken) + { + var albumId = Mapping.GetId(info.ProviderIds, YandexProviderIds.Album); + if (albumId is not null) + { + var byId = await _client.GetAlbumAsync(albumId.Value, cancellationToken).ConfigureAwait(false); + if (byId is not null) + { + return byId; + } + } + + var albums = await SearchAlbumsAsync(info, cancellationToken).ConfigureAwait(false); + var match = MatchScoring.FindBestAlbum( + albums, + info.Name, + info.AlbumArtists, + info.Year, + config.MatchThreshold); + return match?.Album; + } + + private async Task> SearchAlbumsAsync(AlbumInfo info, CancellationToken cancellationToken) + { + var artist = info.AlbumArtists.FirstOrDefault(); + var query = string.IsNullOrWhiteSpace(artist) ? info.Name : $"{artist} {info.Name}"; + var albums = await _client.SearchAlbumsAsync(query, cancellationToken).ConfigureAwait(false); + if (albums.Count == 0 && !string.IsNullOrWhiteSpace(info.Name)) + { + albums = await _client.SearchAlbumsAsync(info.Name, cancellationToken).ConfigureAwait(false); + } + + return albums; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicArtistProvider.cs b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicArtistProvider.cs new file mode 100644 index 0000000..cb20b1b --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicArtistProvider.cs @@ -0,0 +1,156 @@ +using System.Globalization; +using Jellyfin.Plugin.YandexMusic.Configuration; +using Jellyfin.Plugin.YandexMusic.Matching; +using Jellyfin.Plugin.YandexMusic.Yandex; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// +/// Metadata provider for music artists. +/// +public class YandexMusicArtistProvider : IRemoteMetadataProvider, IHasOrder +{ + private readonly YandexMusicClient _client; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public YandexMusicArtistProvider(YandexMusicClient client, ILogger logger) + { + _client = client; + _logger = logger; + } + + /// + public string Name => Mapping.ProviderName; + + /// + public int Order => 1; + + /// + public async Task> GetMetadata(ArtistInfo info, CancellationToken cancellationToken) + { + var result = new MetadataResult { Item = new MusicArtist() }; + var config = Plugin.Instance?.Configuration ?? new PluginConfiguration(); + if (!config.EnableArtistMetadata) + { + return result; + } + + try + { + var artist = await ResolveArtistAsync(info, cancellationToken).ConfigureAwait(false); + if (artist is null) + { + return result; + } + + var details = await _client.GetArtistInfoAsync(artist.Id, cancellationToken).ConfigureAwait(false); + var item = result.Item; + item.Name = artist.Name ?? info.Name; + item.Genres = await Mapping.GenresAsync(_client, null, artist.Genres, cancellationToken) + .ConfigureAwait(false); + + if (!string.IsNullOrWhiteSpace(details?.Description)) + { + item.Overview = details!.Description; + } + else if (!string.IsNullOrWhiteSpace(artist.Description)) + { + item.Overview = artist.Description; + } + + item.SetProviderId(YandexProviderIds.Artist, artist.Id.ToString(CultureInfo.InvariantCulture)); + + var covers = new List(); + if (details?.Covers is { Count: > 0 }) + { + covers.AddRange(details.Covers.Select(c => c.Uri)); + } + + covers.Add(artist.Cover?.Uri); + covers.Add(artist.OgImage); + covers = covers.Where(c => !string.IsNullOrWhiteSpace(c)).Distinct(StringComparer.Ordinal).ToList(); + + if (covers.Count > 0) + { + Mapping.AddPrimaryImage(result, covers[0], 1200); + foreach (var cover in covers.Skip(1).Take(4)) + { + Mapping.AddImage(result, cover, ImageType.Backdrop, 1920); + } + } + + result.HasMetadata = true; + result.QueriedById = Mapping.GetId(info.ProviderIds, YandexProviderIds.Artist) is not null; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Yandex Music failed to provide artist metadata for {Name}", info.Name); + } + + return result; + } + + /// + public async Task> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken) + { + var results = new List(); + try + { + var artists = await _client.SearchArtistsAsync(searchInfo.Name ?? string.Empty, cancellationToken) + .ConfigureAwait(false); + foreach (var artist in artists) + { + results.Add(new RemoteSearchResult + { + Name = artist.Name, + ImageUrl = YandexMusicClient.BuildCoverUrl(artist.Cover?.Uri ?? artist.OgImage, 300), + ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [YandexProviderIds.Artist] = artist.Id.ToString(CultureInfo.InvariantCulture) + }, + SearchProviderName = Name + }); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Yandex Music artist search failed for {Name}", searchInfo.Name); + } + + return results; + } + + /// + public Task GetImageResponse(string url, CancellationToken cancellationToken) + => ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken); + + private async Task ResolveArtistAsync(ArtistInfo info, CancellationToken cancellationToken) + { + var artistId = Mapping.GetId(info.ProviderIds, YandexProviderIds.Artist); + if (artistId is not null) + { + var byId = await _client.GetArtistAsync(artistId.Value, cancellationToken).ConfigureAwait(false); + if (byId is not null) + { + return byId; + } + } + + var artists = await _client.SearchArtistsAsync(info.Name ?? string.Empty, cancellationToken).ConfigureAwait(false); + var match = MatchScoring.FindBestArtist(artists, info.Name); + if (match is null) + { + return null; + } + + return await _client.GetArtistAsync(match.Id, cancellationToken).ConfigureAwait(false) ?? match; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicExternalIds.cs b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicExternalIds.cs new file mode 100644 index 0000000..3795429 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicExternalIds.cs @@ -0,0 +1,99 @@ +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// Track external id. +public class YandexMusicTrackExternalId : IExternalId +{ + /// + public string ProviderName => Mapping.ProviderName; + + /// + public string Key => YandexProviderIds.Track; + + /// + public ExternalIdMediaType? Type => ExternalIdMediaType.Track; + + /// + public bool Supports(IHasProviderIds item) => item is Audio; +} + +/// Album external id. +public class YandexMusicAlbumExternalId : IExternalId +{ + /// + public string ProviderName => Mapping.ProviderName; + + /// + public string Key => YandexProviderIds.Album; + + /// + public ExternalIdMediaType? Type => ExternalIdMediaType.Album; + + /// + public bool Supports(IHasProviderIds item) => item is MusicAlbum; +} + +/// Artist external id. +public class YandexMusicArtistExternalId : IExternalId +{ + /// + public string ProviderName => Mapping.ProviderName; + + /// + public string Key => YandexProviderIds.Artist; + + /// + public ExternalIdMediaType? Type => ExternalIdMediaType.Artist; + + /// + public bool Supports(IHasProviderIds item) => item is MusicArtist; +} + +/// Links to music.yandex.ru on item pages. +public class YandexMusicExternalUrlProvider : IExternalUrlProvider +{ + /// + public string Name => Mapping.ProviderName; + + /// + public IEnumerable GetExternalUrls(BaseItem item) + { + switch (item) + { + case MusicAlbum album: + var albumId = album.GetProviderId(YandexProviderIds.Album); + if (!string.IsNullOrEmpty(albumId)) + { + yield return $"https://music.yandex.ru/album/{albumId}"; + } + + break; + + case MusicArtist artist: + var artistId = artist.GetProviderId(YandexProviderIds.Artist); + if (!string.IsNullOrEmpty(artistId)) + { + yield return $"https://music.yandex.ru/artist/{artistId}"; + } + + break; + + case Audio audio: + var trackId = audio.GetProviderId(YandexProviderIds.Track); + var trackAlbumId = audio.GetProviderId(YandexProviderIds.Album); + if (!string.IsNullOrEmpty(trackId)) + { + yield return string.IsNullOrEmpty(trackAlbumId) + ? $"https://music.yandex.ru/track/{trackId}" + : $"https://music.yandex.ru/album/{trackAlbumId}/track/{trackId}"; + } + + break; + } + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicImageProvider.cs b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicImageProvider.cs new file mode 100644 index 0000000..a1a5027 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicImageProvider.cs @@ -0,0 +1,216 @@ +using System.Globalization; +using System.Net; +using System.Net.Http.Headers; +using Jellyfin.Plugin.YandexMusic.Configuration; +using Jellyfin.Plugin.YandexMusic.Matching; +using Jellyfin.Plugin.YandexMusic.Yandex; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// +/// Cover art provider. +/// +public class YandexMusicImageProvider : IRemoteImageProvider, IHasOrder +{ + private readonly YandexMusicClient _client; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public YandexMusicImageProvider(YandexMusicClient client, ILogger logger) + { + _client = client; + _logger = logger; + } + + /// + public string Name => Mapping.ProviderName; + + /// + public int Order => 1; + + /// + public bool Supports(BaseItem item) => item is Audio or MusicAlbum or MusicArtist; + + /// + public IEnumerable GetSupportedImages(BaseItem item) + => item is MusicArtist ? [ImageType.Primary, ImageType.Backdrop] : [ImageType.Primary]; + + /// + public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) + { + var config = Plugin.Instance?.Configuration ?? new PluginConfiguration(); + if (!config.EnableImages) + { + return []; + } + + try + { + var covers = item switch + { + Audio audio => await GetAudioCoversAsync(audio, config, cancellationToken).ConfigureAwait(false), + MusicAlbum album => await GetAlbumCoversAsync(album, config, cancellationToken).ConfigureAwait(false), + MusicArtist artist => await GetArtistCoversAsync(artist, cancellationToken).ConfigureAwait(false), + _ => new List<(string Url, ImageType Type, int Size)>() + }; + + return covers.Select(c => new RemoteImageInfo + { + ProviderName = Name, + Url = c.Url, + Type = c.Type, + Width = c.Size, + Height = c.Size + }).ToArray(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Yandex Music failed to find images for {Name}", item.Name); + return []; + } + } + + /// + public async Task GetImageResponse(string url, CancellationToken cancellationToken) + { + var bytes = await _client.GetImageBytesAsync(url, cancellationToken).ConfigureAwait(false); + if (bytes is null) + { + return new HttpResponseMessage(HttpStatusCode.NotFound); + } + + var content = new ByteArrayContent(bytes); + content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; + } + + private async Task> GetAudioCoversAsync( + Audio audio, + PluginConfiguration config, + CancellationToken cancellationToken) + { + var trackId = Mapping.GetId(audio, YandexProviderIds.Track); + if (trackId is not null) + { + var track = await _client.GetTrackAsync(trackId.Value, cancellationToken).ConfigureAwait(false); + if (track is not null) + { + return Collect(track.CoverUri ?? track.Albums.FirstOrDefault()?.CoverUri, ImageType.Primary); + } + } + + var albumId = Mapping.GetId(audio, YandexProviderIds.Album); + if (albumId is not null) + { + var album = await _client.GetAlbumAsync(albumId.Value, cancellationToken).ConfigureAwait(false); + if (album is not null) + { + return Collect(album.CoverUri, ImageType.Primary); + } + } + + var tracks = await _client.SearchTracksAsync($"{audio.Artists.FirstOrDefault()} {audio.Name}", cancellationToken) + .ConfigureAwait(false); + var match = MatchScoring.FindBestTrack( + tracks, + audio.Name, + audio.Artists, + MatchScoring.TicksToMilliseconds(audio.RunTimeTicks), + config.MatchThreshold, + config.DurationToleranceSeconds); + return match is null + ? [] + : Collect(match.Value.Track.CoverUri ?? match.Value.Track.Albums.FirstOrDefault()?.CoverUri, ImageType.Primary); + } + + private async Task> GetAlbumCoversAsync( + MusicAlbum album, + PluginConfiguration config, + CancellationToken cancellationToken) + { + var albumId = Mapping.GetId(album, YandexProviderIds.Album); + if (albumId is not null) + { + var byId = await _client.GetAlbumAsync(albumId.Value, cancellationToken).ConfigureAwait(false); + if (byId is not null) + { + return Collect(byId.CoverUri, ImageType.Primary, 1200); + } + } + + var artist = album.AlbumArtists.FirstOrDefault(); + var query = string.IsNullOrWhiteSpace(artist) ? album.Name : $"{artist} {album.Name}"; + var albums = await _client.SearchAlbumsAsync(query, cancellationToken).ConfigureAwait(false); + var match = MatchScoring.FindBestAlbum( + albums, + album.Name, + album.AlbumArtists, + album.ProductionYear, + config.MatchThreshold); + return match is null + ? [] + : Collect(match.Value.Album.CoverUri, ImageType.Primary, 1200); + } + + private async Task> GetArtistCoversAsync( + MusicArtist artist, + CancellationToken cancellationToken) + { + var artistId = Mapping.GetId(artist, YandexProviderIds.Artist); + ArtistDto? dto = null; + if (artistId is not null) + { + dto = await _client.GetArtistAsync(artistId.Value, cancellationToken).ConfigureAwait(false); + } + else + { + var artists = await _client.SearchArtistsAsync(artist.Name, cancellationToken).ConfigureAwait(false); + dto = MatchScoring.FindBestArtist(artists, artist.Name); + } + + if (dto is null) + { + return []; + } + + var covers = new List<(string Url, ImageType Type, int Size)>(); + var details = await _client.GetArtistInfoAsync(dto.Id, cancellationToken).ConfigureAwait(false); + var uris = new List(); + if (details?.Covers is { Count: > 0 }) + { + uris.AddRange(details.Covers.Select(c => c.Uri)); + } + + uris.Add(dto.Cover?.Uri); + uris.Add(dto.OgImage); + + var primaryAdded = false; + foreach (var uri in uris.Where(u => !string.IsNullOrWhiteSpace(u)).Distinct(StringComparer.Ordinal)) + { + var url = YandexMusicClient.BuildCoverUrl(uri, primaryAdded ? 1920 : 1200); + if (url is null) + { + continue; + } + + covers.Add((url, primaryAdded ? ImageType.Backdrop : ImageType.Primary, primaryAdded ? 1920 : 1200)); + primaryAdded = true; + } + + return covers; + } + + private static List<(string Url, ImageType Type, int Size)> Collect(string? coverUri, ImageType type, int size = 1000) + { + var url = YandexMusicClient.BuildCoverUrl(coverUri, size); + return url is null ? [] : [(url, type, size)]; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicLyricProvider.cs b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicLyricProvider.cs new file mode 100644 index 0000000..b82ce45 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicLyricProvider.cs @@ -0,0 +1,166 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; +using Jellyfin.Plugin.YandexMusic.Configuration; +using Jellyfin.Plugin.YandexMusic.Matching; +using Jellyfin.Plugin.YandexMusic.Yandex; +using MediaBrowser.Controller.Lyrics; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Lyrics; +using MediaBrowser.Model.Providers; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// +/// Lyrics provider backed by Yandex Music (requires an OAuth token). +/// +public class YandexMusicLyricProvider : ILyricProvider, IHasOrder +{ + private static readonly ConcurrentDictionary Cache = new(); + + private readonly YandexMusicClient _client; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public YandexMusicLyricProvider(YandexMusicClient client, ILogger logger) + { + _client = client; + _logger = logger; + } + + /// + public string Name => Mapping.ProviderName; + + /// + public int Order => 1; + + /// + public async Task> SearchAsync(LyricSearchRequest request, CancellationToken cancellationToken) + { + var config = Plugin.Instance?.Configuration ?? new PluginConfiguration(); + if (!config.EnableLyrics || !YandexMusicClient.HasToken) + { + return []; + } + + try + { + var trackId = Mapping.GetId(request.ProviderIds, YandexProviderIds.Track); + TrackDto? track = null; + if (trackId is not null) + { + track = await _client.GetTrackAsync(trackId.Value, cancellationToken).ConfigureAwait(false); + } + + if (track is null) + { + var artist = request.ArtistNames?.FirstOrDefault() ?? request.AlbumArtistsNames?.FirstOrDefault(); + var query = string.IsNullOrWhiteSpace(artist) + ? request.SongName + : $"{artist} {request.SongName}"; + var tracks = await _client.SearchTracksAsync(query ?? string.Empty, cancellationToken).ConfigureAwait(false); + var durationMs = request.Duration is null ? 0 : request.Duration.Value / TimeSpan.TicksPerMillisecond; + var artists = (IReadOnlyList?)request.ArtistNames + ?? request.AlbumArtistsNames + ?? Array.Empty(); + var match = MatchScoring.FindBestTrack( + tracks, + request.SongName, + artists, + durationMs, + config.MatchThreshold, + config.DurationToleranceSeconds); + track = match?.Track; + } + + if (track is null) + { + return []; + } + + if (track.LyricsAvailable is false && track.LyricsInfo is { HasLyrics: false }) + { + return []; + } + + var lyrics = await GetLyricsTextAsync(track.Id, cancellationToken).ConfigureAwait(false); + if (lyrics is null) + { + return []; + } + + var (text, format) = lyrics.Value; + return + [ + new RemoteLyricInfo + { + Id = track.Id.ToString(CultureInfo.InvariantCulture), + ProviderName = Name, + Metadata = new LyricMetadata + { + Title = track.Title, + Artist = string.Join(", ", track.Artists.Select(a => a.Name).Where(n => !string.IsNullOrWhiteSpace(n))), + Album = track.Albums.FirstOrDefault()?.Title, + Length = request.Duration, + IsSynced = string.Equals(format, "lrc", StringComparison.OrdinalIgnoreCase) + }, + Lyrics = new LyricResponse + { + Stream = new MemoryStream(Encoding.UTF8.GetBytes(text)), + Format = format + } + } + ]; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, "Yandex Music lyrics search failed for {Song}", request.SongName); + return []; + } + } + + /// + public async Task GetLyricsAsync(string id, CancellationToken cancellationToken) + { + if (!long.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var trackId)) + { + return null; + } + + var lyrics = await GetLyricsTextAsync(trackId, cancellationToken).ConfigureAwait(false); + if (lyrics is null) + { + return null; + } + + return new LyricResponse + { + Stream = new MemoryStream(Encoding.UTF8.GetBytes(lyrics.Value.Text)), + Format = lyrics.Value.Format + }; + } + + private async Task<(string Text, string Format)?> GetLyricsTextAsync(long trackId, CancellationToken cancellationToken) + { + if (Cache.TryGetValue(trackId, out var cached) && DateTime.UtcNow - cached.At < TimeSpan.FromHours(2)) + { + return (cached.Text, cached.Format); + } + + foreach (var format in new[] { "LRC", "TEXT" }) + { + var text = await _client.GetLyricsTextAsync(trackId, format, cancellationToken).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(text)) + { + var normalizedFormat = format == "LRC" ? "lrc" : "txt"; + Cache[trackId] = (text, normalizedFormat, DateTime.UtcNow); + return (text, normalizedFormat); + } + } + + return null; + } +} diff --git a/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicSongProvider.cs b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicSongProvider.cs new file mode 100644 index 0000000..a07eb48 --- /dev/null +++ b/Jellyfin.Plugin.YandexMusic/Providers/YandexMusicSongProvider.cs @@ -0,0 +1,268 @@ +using System.Globalization; +using Jellyfin.Plugin.YandexMusic.Configuration; +using Jellyfin.Plugin.YandexMusic.Matching; +using Jellyfin.Plugin.YandexMusic.Yandex; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.YandexMusic.Providers; + +/// +/// Metadata provider for individual songs (Audio items). +/// +public class YandexMusicSongProvider : IRemoteMetadataProvider, IHasOrder +{ + private readonly YandexMusicClient _client; + private readonly ILibraryManager _libraryManager; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public YandexMusicSongProvider( + YandexMusicClient client, + ILibraryManager libraryManager, + ILogger logger) + { + _client = client; + _libraryManager = libraryManager; + _logger = logger; + } + + /// + public string Name => Mapping.ProviderName; + + /// + public int Order => 1; + + /// + public async Task> GetMetadata(SongInfo info, CancellationToken cancellationToken) + { + var result = new MetadataResult