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,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