Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
106e8f09e0 | ||
|
|
61028e53fe | ||
|
|
f5674bec6a | ||
|
|
230616e4fc | ||
|
|
0dbf427ce1 | ||
|
|
84e3ea34c8 | ||
|
|
16515c5166 |
No files matched your search
@@ -0,0 +1,186 @@
|
||||
using Jellyfin.Data.Enums;
|
||||
using Jellyfin.Plugin.YandexMusic.Providers;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.Audio;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic;
|
||||
|
||||
/// <summary>
|
||||
/// Repairs music metadata links after a Jellyfin 10 -> 12 migration:
|
||||
/// fills AlbumArtists, writes Artists/Genres into the new item-value tables and creates person links.
|
||||
/// </summary>
|
||||
public class AlbumArtistTask : IScheduledTask
|
||||
{
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly IDtoService _dtoService;
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly ILogger<AlbumArtistTask> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AlbumArtistTask"/> class.
|
||||
/// </summary>
|
||||
public AlbumArtistTask(
|
||||
ILibraryManager libraryManager,
|
||||
IDtoService dtoService,
|
||||
YandexMusicClient client,
|
||||
ILogger<AlbumArtistTask> logger)
|
||||
{
|
||||
_libraryManager = libraryManager;
|
||||
_dtoService = dtoService;
|
||||
_client = client;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => "Yandex Music: исправить исполнителей и жанры";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "YandexMusicAlbumArtists";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => "Заново получает исполнителей и жанры из Яндекса и записывает их в новую модель Jellyfin 12, включая связи артистов.";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Category => "Yandex Music";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var items = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
Recursive = true,
|
||||
IncludeItemTypes = [BaseItemKind.Audio],
|
||||
IsVirtualItem = false
|
||||
}).OfType<Audio>().ToList();
|
||||
|
||||
var dtoOptions = new DtoOptions(true);
|
||||
var updated = 0;
|
||||
for (var i = 0; i < items.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var item = items[i];
|
||||
|
||||
var dto = _dtoService.GetBaseItemDto(item, dtoOptions);
|
||||
var dtoArtists = (dto.Artists ?? [])
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
var dtoAlbumArtists = (dto.AlbumArtists ?? [])
|
||||
.Select(a => a.Name)
|
||||
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||
.Select(n => n!)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
var dtoGenres = (dto.Genres ?? [])
|
||||
.Where(g => !string.IsNullOrWhiteSpace(g))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var finalArtists = dtoArtists;
|
||||
var finalAlbumArtists = dtoAlbumArtists;
|
||||
var finalGenres = dtoGenres;
|
||||
|
||||
var trackId = item.GetProviderId(YandexProviderIds.Track);
|
||||
if (long.TryParse(trackId, out var yandexTrackId))
|
||||
{
|
||||
var track = await _client.GetTrackAsync(yandexTrackId, cancellationToken).ConfigureAwait(false);
|
||||
if (track is not null)
|
||||
{
|
||||
var album = track.Albums.FirstOrDefault();
|
||||
if (album is not null)
|
||||
{
|
||||
album = await _client.GetAlbumAsync(album.Id, cancellationToken).ConfigureAwait(false) ?? album;
|
||||
}
|
||||
|
||||
var trackArtists = track.Artists
|
||||
.Select(a => a.Name)
|
||||
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||
.Select(n => n!)
|
||||
.ToArray();
|
||||
var albumArtists = (album?.Artists ?? [])
|
||||
.Select(a => a.Name)
|
||||
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||
.Select(n => n!)
|
||||
.ToArray();
|
||||
|
||||
if (trackArtists.Length > 0)
|
||||
{
|
||||
finalArtists = trackArtists;
|
||||
}
|
||||
|
||||
if (albumArtists.Length > 0)
|
||||
{
|
||||
finalAlbumArtists = albumArtists;
|
||||
}
|
||||
|
||||
var primaryArtist = track.Artists.FirstOrDefault(a => a.Id > 0);
|
||||
var artistGenres = primaryArtist is null
|
||||
? Array.Empty<string>()
|
||||
: await _client.GetArtistGenresAsync(primaryArtist.Id, cancellationToken).ConfigureAwait(false);
|
||||
var genres = await Mapping.GenresAsync(_client, album?.Genre, artistGenres, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (genres.Length > 0)
|
||||
{
|
||||
finalGenres = genres;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (finalArtists.Length > 0)
|
||||
{
|
||||
item.Artists = finalArtists;
|
||||
}
|
||||
|
||||
if (finalAlbumArtists.Length > 0)
|
||||
{
|
||||
item.AlbumArtists = finalAlbumArtists;
|
||||
}
|
||||
else if (AlbumArtistCache.TryGet(item.Path, out var cached))
|
||||
{
|
||||
item.AlbumArtists = cached;
|
||||
}
|
||||
else if (item.Artists.Count > 0)
|
||||
{
|
||||
item.AlbumArtists = [item.Artists[0]];
|
||||
}
|
||||
|
||||
if (finalGenres.Length > 0)
|
||||
{
|
||||
item.Genres = finalGenres;
|
||||
}
|
||||
|
||||
await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var people = new List<PersonInfo>();
|
||||
foreach (var name in item.AlbumArtists)
|
||||
{
|
||||
people.Add(new PersonInfo { Name = name, Type = PersonKind.AlbumArtist });
|
||||
}
|
||||
|
||||
foreach (var name in item.Artists)
|
||||
{
|
||||
people.Add(new PersonInfo { Name = name, Type = PersonKind.Artist });
|
||||
}
|
||||
|
||||
if (people.Count > 0)
|
||||
{
|
||||
await _libraryManager.UpdatePeopleAsync(item, people, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
updated++;
|
||||
progress.Report(100.0 * (i + 1) / Math.Max(1, items.Count));
|
||||
}
|
||||
|
||||
_logger.LogInformation("Yandex Music: repaired metadata links for {Updated} tracks", updated);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() => [];
|
||||
}
|
||||
@@ -72,4 +72,9 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
/// Gets or sets a value indicating whether labels are written as studios.
|
||||
/// </summary>
|
||||
public bool EnableLabels { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether composers and lyricists are fetched from track credits.
|
||||
/// </summary>
|
||||
public bool EnableCredits { get; set; } = true;
|
||||
}
|
||||
@@ -85,6 +85,12 @@
|
||||
<span>Лейблы (как студии)</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="EnableCredits" type="checkbox" is="emby-checkbox" />
|
||||
<span>Композиторы и авторы текста</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="verticalSection">
|
||||
@@ -194,6 +200,7 @@
|
||||
document.querySelector('#EnableLyrics').checked = config.EnableLyrics;
|
||||
document.querySelector('#EnableGenres').checked = config.EnableGenres;
|
||||
document.querySelector('#EnableLabels').checked = config.EnableLabels;
|
||||
document.querySelector('#EnableCredits').checked = config.EnableCredits;
|
||||
document.querySelector('#UseYandexAlbumName').checked = config.UseYandexAlbumName;
|
||||
document.querySelector('#UseYandexYear').checked = config.UseYandexYear;
|
||||
document.querySelector('#MatchThreshold').value = config.MatchThreshold;
|
||||
@@ -225,6 +232,7 @@
|
||||
config.EnableLyrics = document.querySelector('#EnableLyrics').checked;
|
||||
config.EnableGenres = document.querySelector('#EnableGenres').checked;
|
||||
config.EnableLabels = document.querySelector('#EnableLabels').checked;
|
||||
config.EnableCredits = document.querySelector('#EnableCredits').checked;
|
||||
config.UseYandexAlbumName = document.querySelector('#UseYandexAlbumName').checked;
|
||||
config.UseYandexYear = document.querySelector('#UseYandexYear').checked;
|
||||
config.MatchThreshold = parseFloat(document.querySelector('#MatchThreshold').value) || 0.72;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<Version>1.0.0.1</Version>
|
||||
<AssemblyVersion>1.0.0.1</AssemblyVersion>
|
||||
<FileVersion>1.0.0.1</FileVersion>
|
||||
<Version>1.0.0.7</Version>
|
||||
<AssemblyVersion>1.0.0.7</AssemblyVersion>
|
||||
<FileVersion>1.0.0.7</FileVersion>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Jellyfin.Plugin.YandexMusic</RootNamespace>
|
||||
<AssemblyName>Jellyfin.Plugin.YandexMusic</AssemblyName>
|
||||
|
||||
@@ -186,21 +186,38 @@ public static class MatchScoring
|
||||
int toleranceSeconds)
|
||||
{
|
||||
(TrackDto Track, double Score)? best = null;
|
||||
var hasArtists = artists.Any(a => !string.IsNullOrWhiteSpace(a));
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
var titleScore = TextMatch.Similarity(title, track.Title);
|
||||
var artistScore = TextMatch.ArtistSimilarity(
|
||||
artists,
|
||||
track.Artists.Select(a => a.Name));
|
||||
var artistScore = hasArtists
|
||||
? TextMatch.ArtistSimilarity(artists, track.Artists.Select(a => a.Name))
|
||||
: 1;
|
||||
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)
|
||||
double score;
|
||||
if (hasArtists)
|
||||
{
|
||||
continue;
|
||||
if (titleScore < 0.68 || artistScore < 0.42)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
score = durationScore is null
|
||||
? (0.6 * titleScore) + (0.4 * artistScore)
|
||||
: (0.5 * titleScore) + (0.3 * artistScore) + (0.2 * durationScore.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
// No artist tags at all: rely on the title and, when available, the duration.
|
||||
if (titleScore < 0.8)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
score = durationScore is null
|
||||
? titleScore
|
||||
: (0.65 * titleScore) + (0.35 * durationScore.Value);
|
||||
}
|
||||
|
||||
if (best is null || score > best.Value.Score)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Album artists resolved by the song provider are not merged into Audio items by Jellyfin,
|
||||
/// so they are remembered here for the custom provider which runs right after the merge.
|
||||
/// </summary>
|
||||
public static class AlbumArtistCache
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, string[]> Cache = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Stores album artists for an audio file path.</summary>
|
||||
public static void Set(string? path, string[] artists)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || artists.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Cache[path] = artists;
|
||||
}
|
||||
|
||||
/// <summary>Gets album artists for an audio file path.</summary>
|
||||
public static bool TryGet(string? path, out string[] artists)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path) && Cache.TryGetValue(path, out var value))
|
||||
{
|
||||
artists = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
artists = [];
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,62 @@ public static class Mapping
|
||||
|
||||
private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
|
||||
/// <summary>Adds composers and lyricists from Yandex track credits.</summary>
|
||||
public static void AddCredits(
|
||||
MediaBrowser.Controller.Providers.MetadataResult<MediaBrowser.Controller.Entities.Audio.Audio> result,
|
||||
IEnumerable<CreditDto> credits)
|
||||
{
|
||||
foreach (var name in CreditValues(credits, IsComposerRole).SelectMany(SplitNames))
|
||||
{
|
||||
result.AddPerson(new MediaBrowser.Controller.Entities.PersonInfo
|
||||
{
|
||||
Name = name,
|
||||
Type = Jellyfin.Data.Enums.PersonKind.Composer
|
||||
});
|
||||
}
|
||||
|
||||
foreach (var name in CreditValues(credits, IsLyricistRole).SelectMany(SplitNames))
|
||||
{
|
||||
result.AddPerson(new MediaBrowser.Controller.Entities.PersonInfo
|
||||
{
|
||||
Name = name,
|
||||
Type = Jellyfin.Data.Enums.PersonKind.Lyricist
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns credit values whose role matches the predicate.</summary>
|
||||
public static IEnumerable<string> CreditValues(IEnumerable<CreditDto> credits, Func<string?, bool> role)
|
||||
=> credits
|
||||
.Where(c => role(c.Title) && !string.IsNullOrWhiteSpace(c.Value))
|
||||
.Select(c => c.Value!);
|
||||
|
||||
/// <summary>Splits a credit value into individual names.</summary>
|
||||
public static IEnumerable<string> SplitNames(string value)
|
||||
=> value
|
||||
.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(v => v.Length > 0);
|
||||
|
||||
/// <summary>Gets a value indicating whether the credit role is a composer.</summary>
|
||||
public static bool IsComposerRole(string? title)
|
||||
=> title is not null
|
||||
&& (title.Contains("музык", StringComparison.OrdinalIgnoreCase)
|
||||
|| title.Contains("composer", StringComparison.OrdinalIgnoreCase)
|
||||
|| title.Equals("music", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Gets a value indicating whether the credit role is a lyricist.</summary>
|
||||
public static bool IsLyricistRole(string? title)
|
||||
=> title is not null
|
||||
&& (title.Contains("текст", StringComparison.OrdinalIgnoreCase)
|
||||
|| title.Contains("lyric", StringComparison.OrdinalIgnoreCase)
|
||||
|| title.Contains("writer", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Gets a value indicating whether the credit role is a label.</summary>
|
||||
public static bool IsLabelRole(string? title)
|
||||
=> title is not null
|
||||
&& (title.Contains("лейбл", StringComparison.OrdinalIgnoreCase)
|
||||
|| title.Contains("label", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Gets a provider id from lookup info.</summary>
|
||||
public static long? GetId(IReadOnlyDictionary<string, string>? ids, string key)
|
||||
{
|
||||
|
||||
@@ -71,7 +71,11 @@ public class YandexMusicAlbumProvider : IRemoteMetadataProvider<MusicAlbum, Albu
|
||||
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)
|
||||
var primaryGenreArtist = album.Artists.FirstOrDefault(a => a.Id > 0);
|
||||
var albumArtistGenres = primaryGenreArtist is null
|
||||
? Array.Empty<string>()
|
||||
: await _client.GetArtistGenresAsync(primaryGenreArtist.Id, cancellationToken).ConfigureAwait(false);
|
||||
item.Genres = await Mapping.GenresAsync(_client, album.Genre, albumArtistGenres, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var labels = Mapping.Labels(album);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using MediaBrowser.Controller.Entities.Audio;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
using MediaBrowser.Model.Entities;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Runs after the standard metadata merge and fixes fields that the Audio metadata service
|
||||
/// does not copy from a remote provider (most importantly AlbumArtists).
|
||||
/// </summary>
|
||||
public class YandexMusicAudioCustomProvider : ICustomMetadataProvider<Audio>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Name => Mapping.ProviderName;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ItemUpdateType> FetchAsync(Audio item, MetadataRefreshOptions options, CancellationToken cancellationToken)
|
||||
{
|
||||
if (AlbumArtistCache.TryGet(item.Path, out var albumArtists) && albumArtists.Length > 0)
|
||||
{
|
||||
if (!item.AlbumArtists.SequenceEqual(albumArtists, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
item.AlbumArtists = albumArtists;
|
||||
return Task.FromResult(ItemUpdateType.MetadataEdit);
|
||||
}
|
||||
|
||||
return Task.FromResult(ItemUpdateType.None);
|
||||
}
|
||||
|
||||
if (item.AlbumArtists.Count == 0 && item.Artists.Count > 0)
|
||||
{
|
||||
item.AlbumArtists = [item.Artists[0]];
|
||||
return Task.FromResult(ItemUpdateType.MetadataEdit);
|
||||
}
|
||||
|
||||
return Task.FromResult(ItemUpdateType.None);
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,9 @@ public class YandexMusicImageProvider : IRemoteImageProvider, IHasOrder
|
||||
}
|
||||
}
|
||||
|
||||
var tracks = await _client.SearchTracksAsync($"{audio.Artists.FirstOrDefault()} {audio.Name}", cancellationToken)
|
||||
var artist = string.Join(" ", audio.Artists.Where(a => !string.IsNullOrWhiteSpace(a))).Trim();
|
||||
var query = string.IsNullOrWhiteSpace(artist) ? audio.Name : $"{artist} {audio.Name}";
|
||||
var tracks = await _client.SearchTracksAsync(query, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var match = MatchScoring.FindBestTrack(
|
||||
tracks,
|
||||
|
||||
@@ -57,7 +57,10 @@ public class YandexMusicLyricProvider : ILyricProvider, IHasOrder
|
||||
|
||||
if (track is null)
|
||||
{
|
||||
var artist = request.ArtistNames?.FirstOrDefault() ?? request.AlbumArtistsNames?.FirstOrDefault();
|
||||
var artist = string.Join(
|
||||
" ",
|
||||
(request.ArtistNames ?? request.AlbumArtistsNames ?? Array.Empty<string>())
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a))).Trim();
|
||||
var query = string.IsNullOrWhiteSpace(artist)
|
||||
? request.SongName
|
||||
: $"{artist} {request.SongName}";
|
||||
@@ -161,6 +164,13 @@ public class YandexMusicLyricProvider : ILyricProvider, IHasOrder
|
||||
}
|
||||
}
|
||||
|
||||
var supplement = await _client.GetSupplementLyricsAsync(trackId, cancellationToken).ConfigureAwait(false);
|
||||
if (!string.IsNullOrWhiteSpace(supplement))
|
||||
{
|
||||
Cache[trackId] = (supplement, "txt", DateTime.UtcNow);
|
||||
return (supplement, "txt");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,26 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
|
||||
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);
|
||||
audio.Album = config.UseYandexAlbumName
|
||||
? album?.Title ?? info.Album
|
||||
: string.IsNullOrWhiteSpace(info.Album) ? album?.Title : info.Album;
|
||||
@@ -101,15 +121,32 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
}
|
||||
|
||||
audio.PremiereDate = Mapping.ParseReleaseDate(album?.ReleaseDate);
|
||||
audio.Genres = await Mapping.GenresAsync(_client, album?.Genre, null, cancellationToken)
|
||||
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);
|
||||
|
||||
var labels = Mapping.Labels(album);
|
||||
if (labels.Length == 0 && !string.IsNullOrWhiteSpace(track.Major?.Name))
|
||||
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;
|
||||
@@ -217,7 +254,7 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
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 artist = string.Join(" ", artists.Where(a => !string.IsNullOrWhiteSpace(a))).Trim();
|
||||
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))
|
||||
|
||||
@@ -66,6 +66,7 @@ public sealed class CoverDto
|
||||
public sealed class TrackDto
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
[JsonConverter(typeof(FlexibleLongConverter))]
|
||||
public long Id { get; set; }
|
||||
|
||||
[JsonPropertyName("realId")]
|
||||
@@ -228,6 +229,22 @@ public sealed class ArtistLinkDto
|
||||
public string? SocialNetwork { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Response of /artists/{id}.</summary>
|
||||
public sealed class ArtistDetailResponse
|
||||
{
|
||||
[JsonPropertyName("artist")]
|
||||
public ArtistDto? Artist { get; set; }
|
||||
|
||||
[JsonPropertyName("albums")]
|
||||
public List<AlbumDto> Albums { get; set; } = [];
|
||||
|
||||
[JsonPropertyName("similarArtists")]
|
||||
public List<ArtistDto> SimilarArtists { get; set; } = [];
|
||||
|
||||
[JsonPropertyName("allCovers")]
|
||||
public List<CoverDto> AllCovers { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Response of /artists/{id}/info.</summary>
|
||||
public sealed class ArtistInfoResponse
|
||||
{
|
||||
@@ -296,6 +313,54 @@ public sealed class GenreTitleDto
|
||||
public string? FullTitle { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Track credits response.</summary>
|
||||
public sealed class CreditsResponse
|
||||
{
|
||||
[JsonPropertyName("result")]
|
||||
public CreditsDto? Result { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Track credits payload.</summary>
|
||||
public sealed class CreditsDto
|
||||
{
|
||||
[JsonPropertyName("credits")]
|
||||
public List<CreditDto> Credits { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>A single credit line.</summary>
|
||||
public sealed class CreditDto
|
||||
{
|
||||
[JsonPropertyName("title")]
|
||||
public string? Title { get; set; }
|
||||
|
||||
[JsonPropertyName("value")]
|
||||
public string? Value { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Track supplement response.</summary>
|
||||
public sealed class SupplementResponse
|
||||
{
|
||||
[JsonPropertyName("result")]
|
||||
public SupplementDto? Result { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Track supplement payload.</summary>
|
||||
public sealed class SupplementDto
|
||||
{
|
||||
[JsonPropertyName("lyrics")]
|
||||
public SupplementLyricsDto? Lyrics { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Lyrics contained in a track supplement.</summary>
|
||||
public sealed class SupplementLyricsDto
|
||||
{
|
||||
[JsonPropertyName("lyrics")]
|
||||
public string? Lyrics { get; set; }
|
||||
|
||||
[JsonPropertyName("fullLyrics")]
|
||||
public string? FullLyrics { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Lyrics lookup response.</summary>
|
||||
public sealed class LyricsResponse
|
||||
{
|
||||
|
||||
@@ -44,6 +44,8 @@ public sealed class YandexMusicClient
|
||||
private readonly SemaphoreSlim _genreLock = new(1, 1);
|
||||
private Dictionary<string, string>? _genreCache;
|
||||
private string _genreCacheLanguage = string.Empty;
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<long, string[]> _artistGenres = new();
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<long, List<CreditDto>> _credits = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicClient"/> class.
|
||||
@@ -154,11 +156,11 @@ public sealed class YandexMusicClient
|
||||
/// <summary>Gets an artist by id.</summary>
|
||||
public async Task<ArtistDto?> GetArtistAsync(long id, CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await GetJsonAsync<YandexResponse<ArtistDto>>(
|
||||
var response = await GetJsonAsync<YandexResponse<ArtistDetailResponse>>(
|
||||
string.Format(CultureInfo.InvariantCulture, "/artists/{0}", id),
|
||||
false,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return response?.Result;
|
||||
return response?.Result?.Artist;
|
||||
}
|
||||
|
||||
/// <summary>Gets the extended artist card (bio, covers, links).</summary>
|
||||
@@ -168,6 +170,38 @@ public sealed class YandexMusicClient
|
||||
false,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Gets an artist's genre ids, cached per artist.</summary>
|
||||
public async Task<string[]> GetArtistGenresAsync(long artistId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_artistGenres.TryGetValue(artistId, out var cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
var artist = await GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false);
|
||||
var genres = artist?.Genres.ToArray() ?? [];
|
||||
_artistGenres[artistId] = genres;
|
||||
return genres;
|
||||
}
|
||||
|
||||
/// <summary>Gets track credits (composers, lyricists, label), cached per track.</summary>
|
||||
public async Task<List<CreditDto>> GetTrackCreditsAsync(long trackId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_credits.TryGetValue(trackId, out var cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
var response = await GetJsonAsync<CreditsResponse>(
|
||||
string.Format(CultureInfo.InvariantCulture, "/tracks/{0}/credits", trackId),
|
||||
false,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var credits = response?.Result?.Credits ?? [];
|
||||
_credits[trackId] = credits;
|
||||
return credits;
|
||||
}
|
||||
|
||||
/// <summary>Gets similar artists and covers.</summary>
|
||||
public async Task<ArtistBriefDto?> GetArtistBriefAsync(long id, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -300,6 +334,31 @@ public sealed class YandexMusicClient
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets plain lyrics from the track supplement endpoint. Works even though the signed
|
||||
/// /lyrics endpoint currently rejects signatures with "Invalid Sign".
|
||||
/// </summary>
|
||||
public async Task<string?> GetSupplementLyricsAsync(long trackId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Token is null || !Config.EnableLyrics)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var response = await GetJsonAsync<SupplementResponse>(
|
||||
string.Format(CultureInfo.InvariantCulture, "/tracks/{0}/supplement", trackId),
|
||||
true,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var text = response?.Result?.Lyrics?.FullLyrics;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
text = response?.Result?.Lyrics?.Lyrics;
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(text) ? null : text.TrimStart('\uFEFF', '\u200B', ' ', '\r', '\n');
|
||||
}
|
||||
|
||||
/// <summary>Downloads an image from an allowed Yandex host.</summary>
|
||||
public async Task<byte[]?> GetImageBytesAsync(string url, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -29,13 +29,18 @@ Dashboard → Plugins → Manage Repositories → добавить URL выше.
|
||||
## Настройка
|
||||
|
||||
Dashboard → Plugins → Yandex Music:
|
||||
|
||||
- **Войти в Яндекс** — OAuth Device Flow: плагин покажет код и ссылку, после подтверждения токен сохранится сам.
|
||||
- Тумблеры для треков/альбомов/исполнителей/обложек/текстов/жанров/лейблов.
|
||||
- **Порог совпадения** — насколько уверенно результат поиска должен совпасть с тегами файла.
|
||||
- **Допуск по длительности** — используется при поиске обложек и текстов.
|
||||
- **Подставлять настоящее название альбома** — по умолчанию выключено.
|
||||
|
||||
## После миграции Jellyfin 10.x → 12.x
|
||||
|
||||
В Jellyfin 12 исполнители и жанры хранятся в новых таблицах связей. Если библиотека переехала со старой версии, эти связи могут быть пустыми, хотя поля у треков заполнены.
|
||||
|
||||
Запустите задачу **Dashboard → Scheduled Tasks → «Yandex Music: исправить исполнителей и жанры»** — она переносит исполнителей, альбомных исполнителей и жанры в новую модель и создаёт связи артистов.
|
||||
|
||||
## Сборка
|
||||
|
||||
```bash
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: "Yandex Music"
|
||||
guid: "f3b9626b-da14-4cbf-8ad1-33b92cfa6656"
|
||||
version: "1.0.0.1"
|
||||
version: "1.0.0.7"
|
||||
targetAbi: "12.4.0.0"
|
||||
framework: "net10.0"
|
||||
overview: "Metadata for music from Yandex Music."
|
||||
@@ -13,4 +13,4 @@ owner: "kirill"
|
||||
artifacts:
|
||||
- "Jellyfin.Plugin.YandexMusic.dll"
|
||||
changelog: >
|
||||
First release.
|
||||
Fill AlbumArtists so Jellyfin creates artists and albums; add composers/lyricists and artist genres.
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
+5
-5
@@ -9,12 +9,12 @@
|
||||
"imageUrl": "",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.0.0.1",
|
||||
"changelog": "First release.",
|
||||
"version": "1.0.0.7",
|
||||
"changelog": "Re-fetch Yandex artists and genres and write them into Jellyfin 12 item links.",
|
||||
"targetAbi": "12.4.0.0",
|
||||
"sourceUrl": "https://git.midns.ru/1xDed/jellyfin-plugin-yandexmusic/raw/branch/main/dist/Jellyfin.Plugin.YandexMusic_1.0.0.1.zip",
|
||||
"checksum": "cf1c452a0c82bbd417086e9629bbc9c0",
|
||||
"timestamp": "2026-11-27T15:58:58Z"
|
||||
"sourceUrl": "https://git.midns.ru/1xDed/jellyfin-plugin-yandexmusic/raw/branch/main/dist/Jellyfin.Plugin.YandexMusic_1.0.0.7.zip",
|
||||
"checksum": "c2f719e7741aba5422d376b2b269c4d4",
|
||||
"timestamp": "2026-11-27T17:00:56Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+5
-4
@@ -3,11 +3,12 @@ set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
VERSION="1.0.0.1"
|
||||
VERSION="1.0.0.7"
|
||||
NAME="Jellyfin.Plugin.YandexMusic"
|
||||
PUBLISH_DIR="publish"
|
||||
ARTIFACTS_DIR="${ARTIFACTS_DIR:-artifacts}"
|
||||
BASE_URL="${BASE_URL:-}"
|
||||
CHANGELOG="${CHANGELOG:-First release.}"
|
||||
DOTNET_BIN="${DOTNET_BIN:-$HOME/.dotnet/dotnet}"
|
||||
|
||||
"$DOTNET_BIN" publish "$NAME/$NAME.csproj" -c Release -o "$PUBLISH_DIR"
|
||||
@@ -21,9 +22,9 @@ ZIP_NAME="${NAME}_${VERSION}.zip"
|
||||
CHECKSUM=$(md5 -q "$ARTIFACTS_DIR/$ZIP_NAME" 2>/dev/null || md5sum "$ARTIFACTS_DIR/$ZIP_NAME" | cut -d' ' -f1)
|
||||
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
python3 - "$ARTIFACTS_DIR" "$ZIP_NAME" "$CHECKSUM" "$TIMESTAMP" "$VERSION" "$BASE_URL" <<'PY'
|
||||
python3 - "$ARTIFACTS_DIR" "$ZIP_NAME" "$CHECKSUM" "$TIMESTAMP" "$VERSION" "$BASE_URL" "$CHANGELOG" <<'PY'
|
||||
import json, sys, os
|
||||
artifacts, zip_name, checksum, timestamp, version, base_url = sys.argv[1:]
|
||||
artifacts, zip_name, checksum, timestamp, version, base_url, changelog = sys.argv[1:]
|
||||
source = f"{base_url.rstrip('/')}/{zip_name}" if base_url else zip_name
|
||||
manifest = [{
|
||||
"guid": "f3b9626b-da14-4cbf-8ad1-33b92cfa6656",
|
||||
@@ -35,7 +36,7 @@ manifest = [{
|
||||
"imageUrl": "",
|
||||
"versions": [{
|
||||
"version": version,
|
||||
"changelog": "First release.",
|
||||
"changelog": changelog,
|
||||
"targetAbi": "12.4.0.0",
|
||||
"sourceUrl": source,
|
||||
"checksum": checksum,
|
||||
|
||||
@@ -77,3 +77,48 @@ if (File.Exists("/tmp/lib_simple.json"))
|
||||
: $"ok {hit.Value.Score:F2} {name} -> {string.Join(", ", hit.Value.Track.Artists.Select(a => a.Name))} - {hit.Value.Track.Title}");
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine("== full track parse ==");
|
||||
foreach (var id in new long[] { 145788571, 240708 })
|
||||
{
|
||||
var full = await client.GetTrackAsync(id, CancellationToken.None);
|
||||
Console.WriteLine(full is null ? $"track {id}: FAILED" : $"track {id}: {full.Title} / {full.Albums.FirstOrDefault()?.Title}");
|
||||
}
|
||||
|
||||
Console.WriteLine("== pipeline sample ==");
|
||||
if (File.Exists("/tmp/lib_simple2.json"))
|
||||
{
|
||||
using var doc2 = System.Text.Json.JsonDocument.Parse(File.ReadAllText("/tmp/lib_simple2.json"));
|
||||
var ok = 0; var fail = 0; var fullFail = 0;
|
||||
foreach (var el in doc2.RootElement.EnumerateArray().Take(120))
|
||||
{
|
||||
var name = el.GetProperty("name").GetString() ?? string.Empty;
|
||||
var libArtists = el.GetProperty("artists").EnumerateArray().Select(x => x.GetString() ?? string.Empty).ToArray();
|
||||
var ticks = el.GetProperty("ticks").GetInt64();
|
||||
var found = await client.SearchTracksAsync($"{libArtists.FirstOrDefault()} {name}", CancellationToken.None);
|
||||
var hit = MatchScoring.FindBestTrack(found, name, libArtists, ticks / 10000, 0.72, 12);
|
||||
if (hit is null) { fail++; Console.WriteLine($"MISS {name}"); continue; }
|
||||
ok++;
|
||||
var full = await client.GetTrackAsync(hit.Value.Track.Id, CancellationToken.None);
|
||||
if (full is null) { fullFail++; Console.WriteLine($"FULL-FAIL {name} -> {hit.Value.Track.Id}"); continue; }
|
||||
var albumId = full.Albums.FirstOrDefault()?.Id ?? 0;
|
||||
var album = albumId > 0 ? await client.GetAlbumAsync(albumId, CancellationToken.None) : null;
|
||||
if (album is null) Console.WriteLine($"ALBUM-FAIL {name} -> {albumId}");
|
||||
}
|
||||
Console.WriteLine($"pipeline: matched {ok}, misses {fail}, full-fetch failures {fullFail}");
|
||||
}
|
||||
|
||||
Console.WriteLine("== artist wrapper ==");
|
||||
var artistDetail = await client.GetArtistAsync(6504263, CancellationToken.None);
|
||||
Console.WriteLine(artistDetail is null ? "artist FAILED" : $"artist {artistDetail.Id} {artistDetail.Name} genres={string.Join(",", artistDetail.Genres)}");
|
||||
Console.WriteLine("== supplement lyrics ==");
|
||||
var supp = await client.GetSupplementLyricsAsync(108719814, CancellationToken.None);
|
||||
Console.WriteLine(supp is null ? "supplement FAILED" : $"supplement {supp.Length} chars");
|
||||
|
||||
Console.WriteLine("== credits ==");
|
||||
var credits = await client.GetTrackCreditsAsync(108719814, CancellationToken.None);
|
||||
var mres = new MediaBrowser.Controller.Providers.MetadataResult<MediaBrowser.Controller.Entities.Audio.Audio> { Item = new MediaBrowser.Controller.Entities.Audio.Audio() };
|
||||
Jellyfin.Plugin.YandexMusic.Providers.Mapping.AddCredits(mres, credits);
|
||||
Console.WriteLine($"credits {credits.Count}: " + string.Join(", ", mres.People?.Select(p => p.Type + ":" + p.Name) ?? []));
|
||||
var ag = await client.GetArtistGenresAsync(6504263, CancellationToken.None);
|
||||
Console.WriteLine("artist genres: " + string.Join(",", ag));
|
||||
Reference in new issue
Block a user