Yandex Music metadata plugin for Jellyfin 12.4
This commit is contained in:
commit
c3dc901337
25 files changed
+3233
No files matched your search
@@ -0,0 +1,26 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>Creates image responses for search results.</summary>
|
||||
internal static class ImageResponseFactory
|
||||
{
|
||||
/// <summary>Downloads an image and wraps it into an HTTP response.</summary>
|
||||
public static async Task<HttpResponseMessage> 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 };
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Provider id keys used by this plugin.</summary>
|
||||
public static class YandexProviderIds
|
||||
{
|
||||
/// <summary>Track id.</summary>
|
||||
public const string Track = "YandexMusicTrack";
|
||||
|
||||
/// <summary>Album id.</summary>
|
||||
public const string Album = "YandexMusicAlbum";
|
||||
|
||||
/// <summary>Artist id.</summary>
|
||||
public const string Artist = "YandexMusicArtist";
|
||||
}
|
||||
|
||||
/// <summary>Shared mapping helpers.</summary>
|
||||
public static class Mapping
|
||||
{
|
||||
/// <summary>Provider display name.</summary>
|
||||
public const string ProviderName = "Yandex Music";
|
||||
|
||||
private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
|
||||
/// <summary>Gets a provider id from lookup info.</summary>
|
||||
public static long? GetId(IReadOnlyDictionary<string, string>? 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;
|
||||
}
|
||||
|
||||
/// <summary>Gets a provider id from an item.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Parses a Yandex release date.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Validates a release year.</summary>
|
||||
public static int? ValidYear(int? year)
|
||||
=> year is >= 1900 and <= 2100 ? year : null;
|
||||
|
||||
/// <summary>Maps a Yandex album genre to a Jellyfin genre name.</summary>
|
||||
public static async Task<string[]> GenresAsync(
|
||||
YandexMusicClient client,
|
||||
string? albumGenre,
|
||||
IEnumerable<string>? artistGenres,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Config.EnableGenres)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new List<string>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Gets label names.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Adds a primary remote image when allowed.</summary>
|
||||
public static void AddPrimaryImage<T>(
|
||||
MediaBrowser.Controller.Providers.MetadataResult<T> 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds a remote image of a given type.</summary>
|
||||
public static void AddImage<T>(
|
||||
MediaBrowser.Controller.Providers.MetadataResult<T> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Metadata provider for music albums.
|
||||
/// </summary>
|
||||
public class YandexMusicAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder
|
||||
{
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly ILogger<YandexMusicAlbumProvider> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicAlbumProvider"/> class.
|
||||
/// </summary>
|
||||
public YandexMusicAlbumProvider(YandexMusicClient client, ILogger<YandexMusicAlbumProvider> logger)
|
||||
{
|
||||
_client = client;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 1;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new MetadataResult<MusicAlbum> { 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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
var results = new List<RemoteSearchResult>();
|
||||
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<string, string>(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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||
|
||||
private async Task<AlbumDto?> 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<List<AlbumDto>> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Metadata provider for music artists.
|
||||
/// </summary>
|
||||
public class YandexMusicArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo>, IHasOrder
|
||||
{
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly ILogger<YandexMusicArtistProvider> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicArtistProvider"/> class.
|
||||
/// </summary>
|
||||
public YandexMusicArtistProvider(YandexMusicClient client, ILogger<YandexMusicArtistProvider> logger)
|
||||
{
|
||||
_client = client;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 1;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new MetadataResult<MusicArtist> { 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<string?>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
var results = new List<RemoteSearchResult>();
|
||||
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<string, string>(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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||
|
||||
private async Task<ArtistDto?> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Track external id.</summary>
|
||||
public class YandexMusicTrackExternalId : IExternalId
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string ProviderName => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => YandexProviderIds.Track;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ExternalIdMediaType? Type => ExternalIdMediaType.Track;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(IHasProviderIds item) => item is Audio;
|
||||
}
|
||||
|
||||
/// <summary>Album external id.</summary>
|
||||
public class YandexMusicAlbumExternalId : IExternalId
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string ProviderName => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => YandexProviderIds.Album;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ExternalIdMediaType? Type => ExternalIdMediaType.Album;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(IHasProviderIds item) => item is MusicAlbum;
|
||||
}
|
||||
|
||||
/// <summary>Artist external id.</summary>
|
||||
public class YandexMusicArtistExternalId : IExternalId
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string ProviderName => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => YandexProviderIds.Artist;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ExternalIdMediaType? Type => ExternalIdMediaType.Artist;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(IHasProviderIds item) => item is MusicArtist;
|
||||
}
|
||||
|
||||
/// <summary>Links to music.yandex.ru on item pages.</summary>
|
||||
public class YandexMusicExternalUrlProvider : IExternalUrlProvider
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Cover art provider.
|
||||
/// </summary>
|
||||
public class YandexMusicImageProvider : IRemoteImageProvider, IHasOrder
|
||||
{
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly ILogger<YandexMusicImageProvider> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicImageProvider"/> class.
|
||||
/// </summary>
|
||||
public YandexMusicImageProvider(YandexMusicClient client, ILogger<YandexMusicImageProvider> logger)
|
||||
{
|
||||
_client = client;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 1;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(BaseItem item) => item is Audio or MusicAlbum or MusicArtist;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
|
||||
=> item is MusicArtist ? [ImageType.Primary, ImageType.Backdrop] : [ImageType.Primary];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IEnumerable<RemoteImageInfo>> 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 [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<HttpResponseMessage> 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<List<(string Url, ImageType Type, int Size)>> 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<List<(string Url, ImageType Type, int Size)>> 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<List<(string Url, ImageType Type, int Size)>> 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<string?>();
|
||||
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)];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Lyrics provider backed by Yandex Music (requires an OAuth token).
|
||||
/// </summary>
|
||||
public class YandexMusicLyricProvider : ILyricProvider, IHasOrder
|
||||
{
|
||||
private static readonly ConcurrentDictionary<long, (string Text, string Format, DateTime At)> Cache = new();
|
||||
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly ILogger<YandexMusicLyricProvider> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicLyricProvider"/> class.
|
||||
/// </summary>
|
||||
public YandexMusicLyricProvider(YandexMusicClient client, ILogger<YandexMusicLyricProvider> logger)
|
||||
{
|
||||
_client = client;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 1;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IEnumerable<RemoteLyricInfo>> 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<string>?)request.ArtistNames
|
||||
?? request.AlbumArtistsNames
|
||||
?? Array.Empty<string>();
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<LyricResponse?> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Metadata provider for individual songs (Audio items).
|
||||
/// </summary>
|
||||
public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>, IHasOrder
|
||||
{
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly ILogger<YandexMusicSongProvider> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicSongProvider"/> class.
|
||||
/// </summary>
|
||||
public YandexMusicSongProvider(
|
||||
YandexMusicClient client,
|
||||
ILibraryManager libraryManager,
|
||||
ILogger<YandexMusicSongProvider> logger)
|
||||
{
|
||||
_client = client;
|
||||
_libraryManager = libraryManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 1;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<MetadataResult<Audio>> GetMetadata(SongInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new MetadataResult<Audio> { Item = new Audio(), QueriedById = false };
|
||||
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
if (!config.EnableSongMetadata)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var track = await ResolveTrackAsync(info, config, cancellationToken).ConfigureAwait(false);
|
||||
if (track is null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var album = track.Albums.FirstOrDefault();
|
||||
if (album is not null)
|
||||
{
|
||||
album = await _client.GetAlbumAsync(album.Id, cancellationToken).ConfigureAwait(false) ?? album;
|
||||
}
|
||||
|
||||
var artistNames = track.Artists
|
||||
.Select(a => a.Name)
|
||||
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||
.Select(n => n!)
|
||||
.ToArray();
|
||||
if (artistNames.Length == 0)
|
||||
{
|
||||
artistNames = info.Artists.ToArray();
|
||||
}
|
||||
|
||||
var albumArtistNames = album?.Artists
|
||||
.Select(a => a.Name)
|
||||
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||
.Select(n => n!)
|
||||
.ToArray() ?? [];
|
||||
if (albumArtistNames.Length == 0)
|
||||
{
|
||||
albumArtistNames = artistNames;
|
||||
}
|
||||
|
||||
var audio = result.Item;
|
||||
if (!string.IsNullOrWhiteSpace(track.Title))
|
||||
{
|
||||
audio.Name = track.Title!;
|
||||
}
|
||||
|
||||
audio.Artists = artistNames;
|
||||
audio.AlbumArtists = albumArtistNames;
|
||||
audio.Album = config.UseYandexAlbumName
|
||||
? album?.Title ?? info.Album
|
||||
: string.IsNullOrWhiteSpace(info.Album) ? album?.Title : info.Album;
|
||||
|
||||
if (config.UseYandexYear)
|
||||
{
|
||||
audio.ProductionYear = Mapping.ValidYear(album?.Year) ?? info.Year;
|
||||
}
|
||||
|
||||
audio.PremiereDate = Mapping.ParseReleaseDate(album?.ReleaseDate);
|
||||
audio.Genres = await Mapping.GenresAsync(_client, album?.Genre, null, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var labels = Mapping.Labels(album);
|
||||
if (labels.Length == 0 && !string.IsNullOrWhiteSpace(track.Major?.Name))
|
||||
{
|
||||
labels = [track.Major!.Name!];
|
||||
}
|
||||
|
||||
if (labels.Length > 0)
|
||||
{
|
||||
audio.Studios = labels;
|
||||
}
|
||||
|
||||
var (index, disc) = FindPosition(album, track.Id);
|
||||
if (index is not null)
|
||||
{
|
||||
audio.IndexNumber = index;
|
||||
audio.ParentIndexNumber = disc;
|
||||
}
|
||||
|
||||
audio.SetProviderId(YandexProviderIds.Track, track.Id.ToString(CultureInfo.InvariantCulture));
|
||||
if (album is not null)
|
||||
{
|
||||
audio.SetProviderId(YandexProviderIds.Album, album.Id.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
var primaryArtist = track.Artists.FirstOrDefault(a => a.Id > 0);
|
||||
if (primaryArtist is not null)
|
||||
{
|
||||
audio.SetProviderId(YandexProviderIds.Artist, primaryArtist.Id.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
Mapping.AddPrimaryImage(result, track.CoverUri ?? album?.CoverUri);
|
||||
result.HasMetadata = true;
|
||||
result.QueriedById = Mapping.GetId(info.ProviderIds, YandexProviderIds.Track) is not null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Yandex Music failed to provide metadata for {Name}", info.Name);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SongInfo searchInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
var results = new List<RemoteSearchResult>();
|
||||
try
|
||||
{
|
||||
var tracks = await SearchTracksAsync(searchInfo, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
results.Add(new RemoteSearchResult
|
||||
{
|
||||
Name = track.Title,
|
||||
Artists = track.Artists
|
||||
.Select(a => new RemoteSearchResult { Name = a.Name })
|
||||
.ToArray(),
|
||||
ImageUrl = YandexMusicClient.BuildCoverUrl(track.CoverUri, 300),
|
||||
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[YandexProviderIds.Track] = track.Id.ToString(CultureInfo.InvariantCulture)
|
||||
},
|
||||
SearchProviderName = Name
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Yandex Music search failed for {Name}", searchInfo.Name);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||
|
||||
private async Task<TrackDto?> ResolveTrackAsync(SongInfo info, PluginConfiguration config, CancellationToken cancellationToken)
|
||||
{
|
||||
var trackId = Mapping.GetId(info.ProviderIds, YandexProviderIds.Track);
|
||||
if (trackId is not null)
|
||||
{
|
||||
var byId = await _client.GetTrackAsync(trackId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (byId is not null)
|
||||
{
|
||||
return byId;
|
||||
}
|
||||
}
|
||||
|
||||
var tracks = await SearchTracksAsync(info, cancellationToken).ConfigureAwait(false);
|
||||
var artists = info.Artists.Count > 0 ? info.Artists : info.AlbumArtists;
|
||||
var durationMs = GetLocalDurationMs(info);
|
||||
var match = MatchScoring.FindBestTrack(
|
||||
tracks,
|
||||
info.Name,
|
||||
artists,
|
||||
durationMs,
|
||||
config.MatchThreshold,
|
||||
config.DurationToleranceSeconds);
|
||||
if (match is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var full = await _client.GetTrackAsync(match.Value.Track.Id, cancellationToken).ConfigureAwait(false);
|
||||
return full ?? match.Value.Track;
|
||||
}
|
||||
|
||||
private async Task<List<TrackDto>> SearchTracksAsync(SongInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
var artists = info.Artists.Count > 0 ? info.Artists : info.AlbumArtists;
|
||||
var artist = artists.FirstOrDefault();
|
||||
var query = string.IsNullOrWhiteSpace(artist) ? info.Name : $"{artist} {info.Name}";
|
||||
var tracks = await _client.SearchTracksAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
if (tracks.Count == 0 && !string.IsNullOrWhiteSpace(info.Name))
|
||||
{
|
||||
tracks = await _client.SearchTracksAsync(info.Name, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return tracks;
|
||||
}
|
||||
|
||||
private long GetLocalDurationMs(SongInfo info)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(info.Path))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var item = _libraryManager.FindByPath(info.Path, false);
|
||||
return item is Audio audio ? MatchScoring.TicksToMilliseconds(audio.RunTimeTicks) : 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Failed to resolve local audio item for {Path}", info.Path);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static (int? Index, int? Disc) FindPosition(AlbumDto? album, long trackId)
|
||||
{
|
||||
if (album is null || album.Volumes.Count == 0)
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
for (var disc = 0; disc < album.Volumes.Count; disc++)
|
||||
{
|
||||
var index = album.Volumes[disc].IndexOf(trackId);
|
||||
if (index >= 0)
|
||||
{
|
||||
return (index + 1, disc + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user