392 lines
14 KiB
C#
392 lines
14 KiB
C#
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 tags = AudioTagReader.Read(info.Path);
|
|
var fileName = AudioTagReader.ParseFileName(info.Path);
|
|
var lookupTitle = tags?.Title ?? fileName.Title ?? info.Name;
|
|
var lookupArtists = tags?.Artists is { Length: > 0 }
|
|
? tags.Artists
|
|
: fileName.Artist is not null
|
|
? [fileName.Artist]
|
|
: (info.Artists.Count > 0 ? info.Artists.ToArray() : info.AlbumArtists.ToArray());
|
|
var lookupAlbum = tags?.Album ?? info.Album;
|
|
|
|
var track = await ResolveTrackAsync(info, config, lookupTitle, lookupArtists, lookupAlbum, 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 = lookupArtists.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;
|
|
|
|
foreach (var name in artistNames)
|
|
{
|
|
result.AddPerson(new MediaBrowser.Controller.Entities.PersonInfo
|
|
{
|
|
Name = name,
|
|
Type = Jellyfin.Data.Enums.PersonKind.Artist
|
|
});
|
|
}
|
|
|
|
foreach (var name in albumArtistNames)
|
|
{
|
|
result.AddPerson(new MediaBrowser.Controller.Entities.PersonInfo
|
|
{
|
|
Name = name,
|
|
Type = Jellyfin.Data.Enums.PersonKind.AlbumArtist
|
|
});
|
|
}
|
|
|
|
AlbumArtistCache.Set(info.Path, albumArtistNames);
|
|
var tagAlbum = tags?.Album;
|
|
audio.Album = config.UseYandexAlbumName
|
|
? album?.Title ?? tagAlbum ?? info.Album
|
|
: !string.IsNullOrWhiteSpace(tagAlbum)
|
|
? tagAlbum
|
|
: string.IsNullOrWhiteSpace(info.Album) ? album?.Title : info.Album;
|
|
|
|
if (config.UseYandexYear)
|
|
{
|
|
audio.ProductionYear = Mapping.ValidYear(album?.Year) ?? tags?.Year ?? info.Year;
|
|
}
|
|
|
|
audio.PremiereDate = Mapping.ParseReleaseDate(album?.ReleaseDate);
|
|
var primaryArtistForGenres = track.Artists.FirstOrDefault(a => a.Id > 0);
|
|
var artistGenres = primaryArtistForGenres is null
|
|
? Array.Empty<string>()
|
|
: await _client.GetArtistGenresAsync(primaryArtistForGenres.Id, cancellationToken).ConfigureAwait(false);
|
|
audio.Genres = await Mapping.GenresAsync(_client, album?.Genre, artistGenres, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
GenreCache.Set(info.Path, audio.Genres);
|
|
ArtistCache.Set(info.Path, artistNames);
|
|
|
|
var labels = Mapping.Labels(album);
|
|
if (labels.Length == 0 && !string.IsNullOrWhiteSpace(track.Major?.Name) && track.Major.Id > 0)
|
|
{
|
|
labels = [track.Major!.Name!];
|
|
}
|
|
|
|
if (config.EnableCredits)
|
|
{
|
|
var credits = await _client.GetTrackCreditsAsync(track.Id, cancellationToken).ConfigureAwait(false);
|
|
Mapping.AddCredits(result, credits);
|
|
if (labels.Length == 0)
|
|
{
|
|
labels = Mapping.CreditValues(credits, Mapping.IsLabelRole)
|
|
.SelectMany(Mapping.SplitNames)
|
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
|
.ToArray();
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
var trackIdText = track.Id.ToString(CultureInfo.InvariantCulture);
|
|
var albumIdText = album?.Id.ToString(CultureInfo.InvariantCulture);
|
|
audio.SetProviderId(YandexProviderIds.Track, trackIdText);
|
|
if (album is not null)
|
|
{
|
|
audio.SetProviderId(YandexProviderIds.Album, albumIdText!);
|
|
}
|
|
|
|
var primaryArtist = track.Artists.FirstOrDefault(a => a.Id > 0);
|
|
var artistIdText = primaryArtist?.Id.ToString(CultureInfo.InvariantCulture);
|
|
if (primaryArtist is not null)
|
|
{
|
|
audio.SetProviderId(YandexProviderIds.Artist, artistIdText!);
|
|
}
|
|
|
|
ProviderIdCache.Set(info.Path, trackIdText, albumIdText, artistIdText);
|
|
|
|
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,
|
|
string? title,
|
|
IReadOnlyList<string> artists,
|
|
string? album,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var durationMs = GetLocalDurationMs(info);
|
|
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)
|
|
{
|
|
// A previously stored id may belong to a wrong match. Keep it only when it
|
|
// still agrees with the embedded tags.
|
|
var storedMatch = MatchScoring.FindBestTrack(
|
|
[byId],
|
|
title,
|
|
artists,
|
|
durationMs,
|
|
config.MatchThreshold,
|
|
config.DurationToleranceSeconds,
|
|
album);
|
|
if (storedMatch is not null)
|
|
{
|
|
return byId;
|
|
}
|
|
}
|
|
}
|
|
|
|
var tracks = await SearchTracksAsync(title, artists, cancellationToken).ConfigureAwait(false);
|
|
var match = MatchScoring.FindBestTrack(
|
|
tracks,
|
|
title,
|
|
artists,
|
|
durationMs,
|
|
config.MatchThreshold,
|
|
config.DurationToleranceSeconds,
|
|
album);
|
|
if (match is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var full = await _client.GetTrackAsync(match.Value.Track.Id, cancellationToken).ConfigureAwait(false);
|
|
return full ?? match.Value.Track;
|
|
}
|
|
|
|
private Task<List<TrackDto>> SearchTracksAsync(SongInfo info, CancellationToken cancellationToken)
|
|
{
|
|
var tags = AudioTagReader.Read(info.Path);
|
|
var fileName = AudioTagReader.ParseFileName(info.Path);
|
|
var title = tags?.Title ?? fileName.Title ?? info.Name;
|
|
var artists = tags?.Artists is { Length: > 0 }
|
|
? tags.Artists
|
|
: fileName.Artist is not null
|
|
? [fileName.Artist]
|
|
: (info.Artists.Count > 0 ? info.Artists.ToArray() : info.AlbumArtists.ToArray());
|
|
return SearchTracksAsync(title, artists, cancellationToken);
|
|
}
|
|
|
|
private async Task<List<TrackDto>> SearchTracksAsync(
|
|
string? title,
|
|
IReadOnlyList<string> artists,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var artistList = artists
|
|
.Where(a => !string.IsNullOrWhiteSpace(a))
|
|
.ToArray();
|
|
var artist = string.Join(" ", artistList).Trim();
|
|
|
|
var queries = new List<string>();
|
|
if (!string.IsNullOrWhiteSpace(artist) && !string.IsNullOrWhiteSpace(title))
|
|
{
|
|
queries.Add($"{artist} {title}");
|
|
}
|
|
|
|
foreach (var part in artistList.SelectMany(TextMatch.SplitArtists).Take(3))
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(part) && !string.IsNullOrWhiteSpace(title))
|
|
{
|
|
queries.Add($"{part} {title}");
|
|
}
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(title))
|
|
{
|
|
queries.Add(title);
|
|
}
|
|
|
|
var results = new Dictionary<long, TrackDto>();
|
|
foreach (var query in queries.Distinct(StringComparer.OrdinalIgnoreCase).Take(5))
|
|
{
|
|
var found = await _client.SearchTracksAsync(query, cancellationToken).ConfigureAwait(false);
|
|
foreach (var track in found)
|
|
{
|
|
results.TryAdd(track.Id, track);
|
|
}
|
|
|
|
if (results.Count >= 20)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
return results.Values.ToList();
|
|
}
|
|
|
|
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 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);
|
|
}
|
|
}
|