Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7106023d49 | ||
|
|
4bb222af8b | ||
|
|
0dbf00a055 | ||
|
|
106e8f09e0 | ||
|
|
61028e53fe | ||
|
|
f5674bec6a |
No files matched your search
@@ -1,39 +1,51 @@
|
||||
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>
|
||||
/// Fills the AlbumArtists field for existing audio items. Jellyfin's Audio metadata merge
|
||||
/// ignores this field, which is why artist and album pages stay empty.
|
||||
/// 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, ILogger<AlbumArtistTask> logger)
|
||||
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: создать исполнителей";
|
||||
public string Name => "Yandex Music: исправить исполнителей и жанры";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "YandexMusicAlbumArtists";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => "Заполняет AlbumArtists и связи исполнителей, чтобы Jellyfin создал страницы исполнителей.";
|
||||
public string Description => "Заново получает исполнителей и жанры из Яндекса и записывает их в новую модель Jellyfin 12, включая связи артистов.";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Category => "Yandex Music";
|
||||
@@ -48,50 +60,127 @@ public class AlbumArtistTask : IScheduledTask
|
||||
IsVirtualItem = false
|
||||
}).OfType<Audio>().ToList();
|
||||
|
||||
var dtoOptions = new DtoOptions(true);
|
||||
var updated = 0;
|
||||
var artistNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var genreNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < items.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var item = items[i];
|
||||
|
||||
string[] artists;
|
||||
if (AlbumArtistCache.TryGet(item.Path, out var cached))
|
||||
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))
|
||||
{
|
||||
artists = cached;
|
||||
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;
|
||||
foreach (var name in finalArtists)
|
||||
{
|
||||
artistNames.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
if (finalAlbumArtists.Length > 0)
|
||||
{
|
||||
item.AlbumArtists = finalAlbumArtists;
|
||||
foreach (var name in finalAlbumArtists)
|
||||
{
|
||||
artistNames.Add(name);
|
||||
}
|
||||
}
|
||||
else if (AlbumArtistCache.TryGet(item.Path, out var cached))
|
||||
{
|
||||
item.AlbumArtists = cached;
|
||||
}
|
||||
else if (item.Artists.Count > 0)
|
||||
{
|
||||
artists = [item.Artists[0]];
|
||||
}
|
||||
else
|
||||
{
|
||||
artists = [];
|
||||
item.AlbumArtists = [item.Artists[0]];
|
||||
}
|
||||
|
||||
if (artists.Length > 0 && !item.AlbumArtists.SequenceEqual(artists, StringComparer.OrdinalIgnoreCase))
|
||||
if (finalGenres.Length > 0)
|
||||
{
|
||||
item.AlbumArtists = artists;
|
||||
await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
|
||||
updated++;
|
||||
item.Genres = finalGenres;
|
||||
foreach (var name in finalGenres)
|
||||
{
|
||||
genreNames.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
var people = new List<MediaBrowser.Controller.Entities.PersonInfo>();
|
||||
await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var people = new List<PersonInfo>();
|
||||
foreach (var name in item.AlbumArtists)
|
||||
{
|
||||
people.Add(new MediaBrowser.Controller.Entities.PersonInfo
|
||||
{
|
||||
Name = name,
|
||||
Type = Jellyfin.Data.Enums.PersonKind.AlbumArtist
|
||||
});
|
||||
people.Add(new PersonInfo { Name = name, Type = PersonKind.AlbumArtist });
|
||||
}
|
||||
|
||||
foreach (var name in item.Artists)
|
||||
{
|
||||
people.Add(new MediaBrowser.Controller.Entities.PersonInfo
|
||||
{
|
||||
Name = name,
|
||||
Type = Jellyfin.Data.Enums.PersonKind.Artist
|
||||
});
|
||||
people.Add(new PersonInfo { Name = name, Type = PersonKind.Artist });
|
||||
}
|
||||
|
||||
if (people.Count > 0)
|
||||
@@ -99,10 +188,51 @@ public class AlbumArtistTask : IScheduledTask
|
||||
await _libraryManager.UpdatePeopleAsync(item, people, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
updated++;
|
||||
progress.Report(100.0 * (i + 1) / Math.Max(1, items.Count));
|
||||
}
|
||||
|
||||
_logger.LogInformation("Yandex Music: updated album artists for {Updated} of {Total} tracks", updated, items.Count);
|
||||
foreach (var name in artistNames)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
var artist = _libraryManager.GetArtist(name);
|
||||
if (artist is not null && artist.DateLastRefreshed == default)
|
||||
{
|
||||
artist.DateLastRefreshed = DateTime.UtcNow;
|
||||
await artist.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Yandex Music: failed to prepare artist {Artist}", name);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var name in genreNames)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
var genre = _libraryManager.GetMusicGenre(name);
|
||||
if (genre is not null && genre.DateLastRefreshed == default)
|
||||
{
|
||||
genre.DateLastRefreshed = DateTime.UtcNow;
|
||||
await genre.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Yandex Music: failed to prepare genre {Genre}", name);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Yandex Music: repaired metadata links for {Updated} tracks, prepared {Artists} artists and {Genres} genres",
|
||||
updated,
|
||||
artistNames.Count,
|
||||
genreNames.Count);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -16,13 +18,20 @@ public class YandexMusicController : ControllerBase
|
||||
private static readonly ConcurrentDictionary<string, DateTimeOffset> Sessions = new();
|
||||
|
||||
private readonly YandexMusicClient _client;
|
||||
private readonly IServerApplicationPaths _paths;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="YandexMusicController"/> class.
|
||||
/// </summary>
|
||||
public YandexMusicController(YandexMusicClient client)
|
||||
public YandexMusicController(
|
||||
YandexMusicClient client,
|
||||
IServerApplicationPaths paths,
|
||||
ILibraryManager libraryManager)
|
||||
{
|
||||
_client = client;
|
||||
_paths = paths;
|
||||
_libraryManager = libraryManager;
|
||||
}
|
||||
|
||||
/// <summary>Starts the device flow.</summary>
|
||||
@@ -88,6 +97,47 @@ public class YandexMusicController : ControllerBase
|
||||
connected ? null : "api.music.yandex.net недоступен");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes broken virtual-folder entries (e.g. a library left without an item id or paths),
|
||||
/// which Jellyfin cannot delete through its own API.
|
||||
/// </summary>
|
||||
[HttpPost("RepairLibraries")]
|
||||
public ActionResult<RepairLibrariesResult> RepairLibraries()
|
||||
{
|
||||
var live = _libraryManager.GetVirtualFolders();
|
||||
var deleted = new List<string>();
|
||||
|
||||
if (Directory.Exists(_paths.DefaultUserViewsPath))
|
||||
{
|
||||
foreach (var directory in Directory.EnumerateDirectories(_paths.DefaultUserViewsPath))
|
||||
{
|
||||
var name = Path.GetFileName(directory);
|
||||
var info = live.FirstOrDefault(v => string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
var broken = info is null
|
||||
|| string.IsNullOrEmpty(info.ItemId)
|
||||
|| info.Locations.Length == 0;
|
||||
if (broken)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
deleted.Add(name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, new { error = ex.Message, name });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new RepairLibrariesResult(
|
||||
deleted,
|
||||
live.Where(v => !deleted.Contains(v.Name, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(v => v.Name)
|
||||
.ToList());
|
||||
}
|
||||
|
||||
/// <summary>Clears the saved token.</summary>
|
||||
[HttpPost("Logout")]
|
||||
public ActionResult Logout()
|
||||
@@ -115,3 +165,6 @@ public record DevicePollResult(string Status, string? Token, string? Error);
|
||||
|
||||
/// <summary>Plugin status.</summary>
|
||||
public record StatusResult(bool Connected, bool HasToken, string? Error);
|
||||
|
||||
/// <summary>Result of the broken-library cleanup.</summary>
|
||||
public record RepairLibrariesResult(List<string> Deleted, List<string> Remaining);
|
||||
@@ -77,4 +77,9 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
/// Gets or sets a value indicating whether composers and lyricists are fetched from track credits.
|
||||
/// </summary>
|
||||
public bool EnableCredits { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the target folder for the "organize into albums" task.
|
||||
/// </summary>
|
||||
public string OrganizeTargetPath { get; set; } = "/movie/music-organized";
|
||||
}
|
||||
@@ -126,6 +126,11 @@
|
||||
<label class="inputLabel inputLabelUnfocused" for="DurationToleranceSeconds">Допуск по длительности, сек</label>
|
||||
<input id="DurationToleranceSeconds" type="number" is="emby-input" min="2" max="60" step="1" />
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="OrganizeTargetPath">Папка для раскладки по альбомам</label>
|
||||
<input id="OrganizeTargetPath" type="text" is="emby-input" />
|
||||
<div class="fieldDescription">Куда задача «разложить по альбомам» создаст хардлинки. По умолчанию /movie/music-organized.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -205,6 +210,7 @@
|
||||
document.querySelector('#UseYandexYear').checked = config.UseYandexYear;
|
||||
document.querySelector('#MatchThreshold').value = config.MatchThreshold;
|
||||
document.querySelector('#DurationToleranceSeconds').value = config.DurationToleranceSeconds;
|
||||
document.querySelector('#OrganizeTargetPath').value = config.OrganizeTargetPath || '/movie/music-organized';
|
||||
Dashboard.hideLoadingMsg();
|
||||
ApiClient.ajax({
|
||||
type: 'GET',
|
||||
@@ -237,6 +243,7 @@
|
||||
config.UseYandexYear = document.querySelector('#UseYandexYear').checked;
|
||||
config.MatchThreshold = parseFloat(document.querySelector('#MatchThreshold').value) || 0.72;
|
||||
config.DurationToleranceSeconds = parseInt(document.querySelector('#DurationToleranceSeconds').value, 10) || 12;
|
||||
config.OrganizeTargetPath = document.querySelector('#OrganizeTargetPath').value || '/movie/music-organized';
|
||||
ApiClient.updatePluginConfiguration(YandexMusicConfig.pluginId, config).then(function (result) {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<Version>1.0.0.5</Version>
|
||||
<AssemblyVersion>1.0.0.5</AssemblyVersion>
|
||||
<FileVersion>1.0.0.5</FileVersion>
|
||||
<Version>1.0.0.12</Version>
|
||||
<AssemblyVersion>1.0.0.12</AssemblyVersion>
|
||||
<FileVersion>1.0.0.12</FileVersion>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Jellyfin.Plugin.YandexMusic</RootNamespace>
|
||||
<AssemblyName>Jellyfin.Plugin.YandexMusic</AssemblyName>
|
||||
@@ -21,6 +21,7 @@
|
||||
<PackageReference Include="Jellyfin.Model" Version="12.4.0">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="TagLibSharp" Version="2.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -81,6 +81,23 @@ public static partial class TextMatch
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Splits a combined artist string on commas.</summary>
|
||||
public static IEnumerable<string> SplitCommaSeparated(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var part in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (part.Length > 0)
|
||||
{
|
||||
yield return part;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Splits a combined artist string ("A, B & C feat. D") into individual names.</summary>
|
||||
public static IEnumerable<string> SplitArtists(string? value)
|
||||
{
|
||||
@@ -183,10 +200,15 @@ public static class MatchScoring
|
||||
IReadOnlyList<string> artists,
|
||||
long durationMs,
|
||||
double threshold,
|
||||
int toleranceSeconds)
|
||||
int toleranceSeconds,
|
||||
string? album = null)
|
||||
{
|
||||
(TrackDto Track, double Score)? best = null;
|
||||
var hasArtists = artists.Any(a => !string.IsNullOrWhiteSpace(a));
|
||||
var artistParts = artists
|
||||
.SelectMany(TextMatch.SplitArtists)
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a))
|
||||
.ToArray();
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
var titleScore = TextMatch.Similarity(title, track.Title);
|
||||
@@ -194,6 +216,18 @@ public static class MatchScoring
|
||||
? TextMatch.ArtistSimilarity(artists, track.Artists.Select(a => a.Name))
|
||||
: 1;
|
||||
var durationScore = DurationScore(durationMs, track.DurationMs, toleranceSeconds);
|
||||
var albumScore = 0.5;
|
||||
if (!string.IsNullOrWhiteSpace(album))
|
||||
{
|
||||
var candidateAlbum = track.Albums.FirstOrDefault()?.Title;
|
||||
albumScore = string.IsNullOrWhiteSpace(candidateAlbum)
|
||||
? 0
|
||||
: TextMatch.Similarity(album, candidateAlbum);
|
||||
}
|
||||
|
||||
var matchedArtistCount = hasArtists
|
||||
? artistParts.Count(a => track.Artists.Any(c => TextMatch.Similarity(a, c.Name) >= 0.7))
|
||||
: 0;
|
||||
|
||||
double score;
|
||||
if (hasArtists)
|
||||
@@ -204,22 +238,25 @@ public static class MatchScoring
|
||||
}
|
||||
|
||||
score = durationScore is null
|
||||
? (0.6 * titleScore) + (0.4 * artistScore)
|
||||
: (0.5 * titleScore) + (0.3 * artistScore) + (0.2 * durationScore.Value);
|
||||
? (0.5 * titleScore) + (0.3 * artistScore) + (0.2 * albumScore)
|
||||
: (0.45 * titleScore) + (0.25 * artistScore) + (0.2 * durationScore.Value) + (0.1 * albumScore);
|
||||
}
|
||||
else
|
||||
{
|
||||
// No artist tags at all: rely on the title and, when available, the duration.
|
||||
// No artist tags at all: rely on the title and, when available, the duration and album.
|
||||
if (titleScore < 0.8)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
score = durationScore is null
|
||||
? titleScore
|
||||
: (0.65 * titleScore) + (0.35 * durationScore.Value);
|
||||
? (0.75 * titleScore) + (0.25 * albumScore)
|
||||
: (0.55 * titleScore) + (0.3 * durationScore.Value) + (0.15 * albumScore);
|
||||
}
|
||||
|
||||
// Prefer a result that matches more of the listed artists when the other signals are equal.
|
||||
score += 0.001 * matchedArtistCount;
|
||||
|
||||
if (best is null || score > best.Value.Score)
|
||||
{
|
||||
best = (track, score);
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Jellyfin.Data.Enums;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.Audio;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Jellyfin-friendly Artist/Album folder tree using hard links, so albums and artists
|
||||
/// are built from folders while the original files stay untouched.
|
||||
/// </summary>
|
||||
public class OrganizeLibraryTask : IScheduledTask
|
||||
{
|
||||
private const string DefaultTargetPath = "/movie/music-organized";
|
||||
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly ILogger<OrganizeLibraryTask> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OrganizeLibraryTask"/> class.
|
||||
/// </summary>
|
||||
public OrganizeLibraryTask(ILibraryManager libraryManager, ILogger<OrganizeLibraryTask> logger)
|
||||
{
|
||||
_libraryManager = libraryManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => "Yandex Music: разложить по альбомам";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "YandexMusicOrganize";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => "Создаёт дерево Исполнитель/Альбом хардлинками, чтобы Jellyfin создал альбомы.";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Category => "Yandex Music";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var targetRoot = Plugin.Instance?.Configuration.OrganizeTargetPath;
|
||||
if (string.IsNullOrWhiteSpace(targetRoot))
|
||||
{
|
||||
targetRoot = DefaultTargetPath;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(targetRoot);
|
||||
|
||||
var items = _libraryManager.GetItemList(new InternalItemsQuery
|
||||
{
|
||||
Recursive = true,
|
||||
IncludeItemTypes = [BaseItemKind.Audio],
|
||||
IsVirtualItem = false
|
||||
}).OfType<Audio>().ToList();
|
||||
|
||||
var linked = 0;
|
||||
var skipped = 0;
|
||||
var failed = 0;
|
||||
|
||||
for (var i = 0; i < items.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var item = items[i];
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(item.Path) || !File.Exists(item.Path))
|
||||
{
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var artist = item.AlbumArtists.FirstOrDefault() ?? item.Artists.FirstOrDefault() ?? "Unknown";
|
||||
var album = string.IsNullOrWhiteSpace(item.Album) ? "Singles" : item.Album;
|
||||
var number = item.IndexNumber is > 0 ? $"{item.IndexNumber.Value:00} - " : string.Empty;
|
||||
var name = number + (string.IsNullOrWhiteSpace(item.Name) ? Path.GetFileNameWithoutExtension(item.Path) : item.Name);
|
||||
var extension = Path.GetExtension(item.Path).ToLowerInvariant();
|
||||
|
||||
var directory = Path.Combine(targetRoot, Sanitize(artist), Sanitize(album));
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
var target = Path.Combine(directory, Sanitize(name) + extension);
|
||||
if (File.Exists(target))
|
||||
{
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryCreateHardLink(item.Path, target))
|
||||
{
|
||||
linked++;
|
||||
}
|
||||
else
|
||||
{
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
failed++;
|
||||
_logger.LogWarning(ex, "Yandex Music: failed to organize {Path}", item.Path);
|
||||
}
|
||||
|
||||
progress.Report(100.0 * (i + 1) / Math.Max(1, items.Count));
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Yandex Music: organized {Linked} files into {Target}, skipped {Skipped}, failed {Failed}",
|
||||
linked,
|
||||
targetRoot,
|
||||
skipped,
|
||||
failed);
|
||||
await Task.CompletedTask.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() => [];
|
||||
|
||||
private static string Sanitize(string value)
|
||||
{
|
||||
var invalid = Path.GetInvalidFileNameChars();
|
||||
var chars = value.Select(c => invalid.Contains(c) ? '_' : c).ToArray();
|
||||
var result = new string(chars).Trim().TrimEnd('.');
|
||||
return string.IsNullOrWhiteSpace(result) ? "Unknown" : result;
|
||||
}
|
||||
|
||||
private static bool TryCreateHardLink(string source, string target)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return CreateHardLinkWindows(target, source, IntPtr.Zero);
|
||||
}
|
||||
|
||||
return LinkUnix(source, target) == 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
|
||||
private static extern int link(string oldpath, string newpath);
|
||||
|
||||
private static int LinkUnix(string oldpath, string newpath) => link(oldpath, newpath);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
private static extern bool CreateHardLinkWindows(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Artists resolved from Yandex for an audio file. Applied after the merge so stale or
|
||||
/// combined artist names from tags do not accumulate between refreshes.
|
||||
/// </summary>
|
||||
public static class ArtistCache
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, string[]> Cache = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Stores 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 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the original embedded tags directly from the file, so matching is not affected by
|
||||
/// metadata previously written into Jellyfin's database.
|
||||
/// </summary>
|
||||
public static class AudioTagReader
|
||||
{
|
||||
/// <summary>Embedded tag values relevant for matching.</summary>
|
||||
public sealed record Tags(
|
||||
string? Title,
|
||||
string[] Artists,
|
||||
string[] AlbumArtists,
|
||||
string? Album,
|
||||
int? Year,
|
||||
string[] Genres,
|
||||
int? Track);
|
||||
|
||||
/// <summary>Reads tags from a media file. Returns null when the file cannot be read.</summary>
|
||||
public static Tags? Read(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var file = TagLib.File.Create(path);
|
||||
var tag = file.Tag;
|
||||
var artists = (tag.Performers ?? [])
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a))
|
||||
.Select(a => a.Trim())
|
||||
.ToArray();
|
||||
var albumArtists = (tag.AlbumArtists ?? [])
|
||||
.Where(a => !string.IsNullOrWhiteSpace(a))
|
||||
.Select(a => a.Trim())
|
||||
.ToArray();
|
||||
|
||||
return new Tags(
|
||||
NullIfEmpty(tag.Title),
|
||||
artists,
|
||||
albumArtists,
|
||||
NullIfEmpty(tag.Album),
|
||||
tag.Year == 0 ? null : (int)tag.Year,
|
||||
(tag.Genres ?? []).Where(g => !string.IsNullOrWhiteSpace(g)).ToArray(),
|
||||
tag.Track == 0 ? null : (int)tag.Track);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses "Artist - Title" from a file name when tags are missing.</summary>
|
||||
public static (string? Artist, string? Title) ParseFileName(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
var name = Path.GetFileNameWithoutExtension(path);
|
||||
var index = name.LastIndexOf(" - ", StringComparison.Ordinal);
|
||||
if (index <= 0 || index + 3 >= name.Length)
|
||||
{
|
||||
return (null, name);
|
||||
}
|
||||
|
||||
return (name[..index].Trim(), name[(index + 3)..].Trim());
|
||||
}
|
||||
|
||||
private static string? NullIfEmpty(string? value)
|
||||
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Normalized genres resolved by the song provider, applied after Jellyfin's metadata merge
|
||||
/// so raw tag ids (rusrap, pop, ...) do not stick to the item.
|
||||
/// </summary>
|
||||
public static class GenreCache
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, string[]> Cache = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Stores genres for an audio file path.</summary>
|
||||
public static void Set(string? path, string[] genres)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || genres.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Cache[path] = genres;
|
||||
}
|
||||
|
||||
/// <summary>Gets genres for an audio file path.</summary>
|
||||
public static bool TryGet(string? path, out string[] genres)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path) && Cache.TryGetValue(path, out var value))
|
||||
{
|
||||
genres = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
genres = [];
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Fallback mapping for Yandex genre ids when the online genre dictionary does not contain them.
|
||||
/// </summary>
|
||||
public static class GenreNameMap
|
||||
{
|
||||
private static readonly Dictionary<string, string> Map = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["rusrap"] = "Русский рэп",
|
||||
["ruspop"] = "Русская поп-музыка",
|
||||
["rusrock"] = "Русский рок",
|
||||
["rap"] = "Рэп и хип-хоп",
|
||||
["hiphop"] = "Хип-хоп",
|
||||
["pop"] = "Поп",
|
||||
["rock"] = "Рок",
|
||||
["allrock"] = "Рок",
|
||||
["alternative"] = "Альтернатива",
|
||||
["indie"] = "Инди",
|
||||
["local-indie"] = "Местное инди",
|
||||
["electronics"] = "Электроника",
|
||||
["electronic"] = "Электроника",
|
||||
["edmgenre"] = "EDM",
|
||||
["dance"] = "Танцевальная",
|
||||
["house"] = "Хаус",
|
||||
["techno"] = "Техно",
|
||||
["trance"] = "Транс",
|
||||
["dubstep"] = "Дабстеп",
|
||||
["drumandbass"] = "Драм-н-бейс",
|
||||
["ambient"] = "Эмбиент",
|
||||
["lounge"] = "Лаундж",
|
||||
["jazz"] = "Джаз",
|
||||
["blues"] = "Блюз",
|
||||
["soul"] = "Соул",
|
||||
["rnb"] = "R&B",
|
||||
["funk"] = "Фанк",
|
||||
["disco"] = "Диско",
|
||||
["classical"] = "Классика",
|
||||
["modern"] = "Современная классика",
|
||||
["soundtrack"] = "Саундтреки",
|
||||
["folk"] = "Фолк",
|
||||
["metal"] = "Метал",
|
||||
["heavymetal"] = "Хэви-метал",
|
||||
["hardrock"] = "Хард-рок",
|
||||
["punk"] = "Панк",
|
||||
["hardcore"] = "Хардкор",
|
||||
["kpop"] = "K-Pop",
|
||||
["jpop"] = "J-Pop",
|
||||
["latin"] = "Латиноамериканская",
|
||||
["reggae"] = "Регги",
|
||||
["country"] = "Кантри",
|
||||
["shanson"] = "Шансон",
|
||||
["children"] = "Детская",
|
||||
["christmas"] = "Новогодняя",
|
||||
["anime"] = "Аниме",
|
||||
["games"] = "Из видеоигр",
|
||||
["experimental"] = "Экспериментальная",
|
||||
["newage"] = "Нью-эйдж",
|
||||
["postrock"] = "Построк",
|
||||
["numetal"] = "Ню-метал",
|
||||
["epicmetal"] = "Эпический",
|
||||
["phonk"] = "Фонк",
|
||||
["hyperpop"] = "Гиперпоп",
|
||||
["metalcoregenre"] = "Металкор",
|
||||
["deathmetal"] = "Дэт-метал",
|
||||
["blackmetal"] = "Блэк-метал",
|
||||
["thrashmetal"] = "Трэш-метал",
|
||||
["classicmetal"] = "Хэви-метал",
|
||||
["progmetal"] = "Прогрессив-метал",
|
||||
["gothicmetal"] = "Готик-метал",
|
||||
["industrial"] = "Индастриал",
|
||||
["postmetal"] = "Постметал",
|
||||
["stonerrock"] = "Стоунер-рок",
|
||||
["prog"] = "Прогрессивный рок",
|
||||
["newwave"] = "New Wave",
|
||||
["rnr"] = "Рок-н-ролл",
|
||||
["folkrock"] = "Фолк-рок",
|
||||
["ukrrock"] = "Украинский рок",
|
||||
["turkishrock"] = "Турецкий рок",
|
||||
["israelirock"] = "Израильский рок",
|
||||
["world"] = "Музыка мира",
|
||||
["classicalmusic"] = "Мировая классика",
|
||||
["easylistening"] = "Лёгкая музыка"
|
||||
};
|
||||
|
||||
/// <summary>Returns a readable genre name for a raw Yandex genre id.</summary>
|
||||
public static string Normalize(string value)
|
||||
{
|
||||
var trimmed = value.Trim();
|
||||
if (trimmed.Length == 0)
|
||||
{
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
if (Map.TryGetValue(trimmed, out var mapped))
|
||||
{
|
||||
return mapped;
|
||||
}
|
||||
|
||||
// Raw ids are ascii with no spaces; keep unknown ones readable instead of dropping data.
|
||||
if (trimmed.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_'))
|
||||
{
|
||||
return trimmed.Replace('_', ' ').Replace('-', ' ');
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/// <summary>Normalizes and deduplicates a genre list.</summary>
|
||||
public static string[] NormalizeAll(IEnumerable<string> genres)
|
||||
=> genres
|
||||
.Select(g => Normalize(g))
|
||||
.Where(g => g.Length > 0)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Provider ids resolved by the song provider. Jellyfin keeps existing ids during a normal
|
||||
/// refresh, so a previously wrong match can stick; the custom provider applies the resolved ids.
|
||||
/// </summary>
|
||||
public static class ProviderIdCache
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, (string Track, string? Album, string? Artist)> Cache =
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Stores ids for an audio file path.</summary>
|
||||
public static void Set(string? path, string track, string? album, string? artist)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(track))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Cache[path] = (track, album, artist);
|
||||
}
|
||||
|
||||
/// <summary>Gets ids for an audio file path.</summary>
|
||||
public static bool TryGet(string? path, out (string Track, string? Album, string? Artist) ids)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path) && Cache.TryGetValue(path, out var value))
|
||||
{
|
||||
ids = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
ids = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||
using MediaBrowser.Controller.Entities.Audio;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
@@ -6,8 +7,8 @@ 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).
|
||||
/// Runs after the standard metadata merge and fixes fields the Audio metadata service
|
||||
/// either does not copy or merges badly: AlbumArtists, duplicated artist names and raw genre ids.
|
||||
/// </summary>
|
||||
public class YandexMusicAudioCustomProvider : ICustomMetadataProvider<Audio>
|
||||
{
|
||||
@@ -17,23 +18,95 @@ public class YandexMusicAudioCustomProvider : ICustomMetadataProvider<Audio>
|
||||
/// <inheritdoc />
|
||||
public Task<ItemUpdateType> FetchAsync(Audio item, MetadataRefreshOptions options, CancellationToken cancellationToken)
|
||||
{
|
||||
if (AlbumArtistCache.TryGet(item.Path, out var albumArtists) && albumArtists.Length > 0)
|
||||
var update = ItemUpdateType.None;
|
||||
|
||||
var artists = NormalizeArtists(item.Artists);
|
||||
if (ArtistCache.TryGet(item.Path, out var cachedArtists))
|
||||
{
|
||||
if (!item.AlbumArtists.SequenceEqual(albumArtists, StringComparer.OrdinalIgnoreCase))
|
||||
artists = NormalizeArtists(cachedArtists);
|
||||
}
|
||||
|
||||
if (!artists.SequenceEqual(item.Artists, StringComparer.Ordinal))
|
||||
{
|
||||
item.Artists = artists;
|
||||
update |= ItemUpdateType.MetadataEdit;
|
||||
}
|
||||
|
||||
string[] albumArtists;
|
||||
if (AlbumArtistCache.TryGet(item.Path, out var cachedAlbumArtists))
|
||||
{
|
||||
albumArtists = NormalizeArtists(cachedAlbumArtists);
|
||||
}
|
||||
else
|
||||
{
|
||||
albumArtists = item.AlbumArtists.Count > 0
|
||||
? NormalizeArtists(item.AlbumArtists)
|
||||
: artists.Length > 0 ? [artists[0]] : [];
|
||||
}
|
||||
|
||||
if (!albumArtists.SequenceEqual(item.AlbumArtists, StringComparer.Ordinal))
|
||||
{
|
||||
item.AlbumArtists = albumArtists;
|
||||
update |= ItemUpdateType.MetadataEdit;
|
||||
}
|
||||
|
||||
if (ProviderIdCache.TryGet(item.Path, out var ids))
|
||||
{
|
||||
if (!string.Equals(item.GetProviderId(YandexProviderIds.Track), ids.Track, StringComparison.Ordinal))
|
||||
{
|
||||
item.AlbumArtists = albumArtists;
|
||||
return Task.FromResult(ItemUpdateType.MetadataEdit);
|
||||
item.SetProviderId(YandexProviderIds.Track, ids.Track);
|
||||
update |= ItemUpdateType.MetadataEdit;
|
||||
}
|
||||
|
||||
return Task.FromResult(ItemUpdateType.None);
|
||||
if (!string.IsNullOrWhiteSpace(ids.Album)
|
||||
&& !string.Equals(item.GetProviderId(YandexProviderIds.Album), ids.Album, StringComparison.Ordinal))
|
||||
{
|
||||
item.SetProviderId(YandexProviderIds.Album, ids.Album!);
|
||||
update |= ItemUpdateType.MetadataEdit;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(ids.Artist)
|
||||
&& !string.Equals(item.GetProviderId(YandexProviderIds.Artist), ids.Artist, StringComparison.Ordinal))
|
||||
{
|
||||
item.SetProviderId(YandexProviderIds.Artist, ids.Artist!);
|
||||
update |= ItemUpdateType.MetadataEdit;
|
||||
}
|
||||
}
|
||||
|
||||
if (item.AlbumArtists.Count == 0 && item.Artists.Count > 0)
|
||||
var sourceGenres = GenreCache.TryGet(item.Path, out var cachedGenres) && cachedGenres.Length > 0
|
||||
? cachedGenres
|
||||
: item.Genres;
|
||||
if (sourceGenres.Length > 0)
|
||||
{
|
||||
item.AlbumArtists = [item.Artists[0]];
|
||||
return Task.FromResult(ItemUpdateType.MetadataEdit);
|
||||
var distinctGenres = GenreNameMap.NormalizeAll(sourceGenres);
|
||||
if (!distinctGenres.SequenceEqual(item.Genres, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
item.Genres = distinctGenres;
|
||||
update |= ItemUpdateType.MetadataEdit;
|
||||
}
|
||||
}
|
||||
|
||||
return Task.FromResult(ItemUpdateType.None);
|
||||
return Task.FromResult(update);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits combined artist strings ("A, B") and removes duplicates. Ampersands are kept
|
||||
/// because they can be part of a single artist name (Miyagi & Andy Panda).
|
||||
/// </summary>
|
||||
public static string[] NormalizeArtists(IEnumerable<string> artists)
|
||||
{
|
||||
var result = new List<string>();
|
||||
foreach (var artist in artists)
|
||||
{
|
||||
foreach (var part in TextMatch.SplitCommaSeparated(artist))
|
||||
{
|
||||
if (!result.Contains(part, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
result.Add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,8 @@ public class YandexMusicImageProvider : IRemoteImageProvider, IHasOrder
|
||||
audio.Artists,
|
||||
MatchScoring.TicksToMilliseconds(audio.RunTimeTicks),
|
||||
config.MatchThreshold,
|
||||
config.DurationToleranceSeconds);
|
||||
config.DurationToleranceSeconds,
|
||||
audio.Album);
|
||||
return match is null
|
||||
? []
|
||||
: Collect(match.Value.Track.CoverUri ?? match.Value.Track.Albums.FirstOrDefault()?.CoverUri, ImageType.Primary);
|
||||
|
||||
@@ -75,7 +75,8 @@ public class YandexMusicLyricProvider : ILyricProvider, IHasOrder
|
||||
artists,
|
||||
durationMs,
|
||||
config.MatchThreshold,
|
||||
config.DurationToleranceSeconds);
|
||||
config.DurationToleranceSeconds,
|
||||
request.AlbumName);
|
||||
track = match?.Track;
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,18 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
|
||||
try
|
||||
{
|
||||
var track = await ResolveTrackAsync(info, config, cancellationToken).ConfigureAwait(false);
|
||||
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;
|
||||
@@ -70,7 +81,7 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
.ToArray();
|
||||
if (artistNames.Length == 0)
|
||||
{
|
||||
artistNames = info.Artists.ToArray();
|
||||
artistNames = lookupArtists.ToArray();
|
||||
}
|
||||
|
||||
var albumArtistNames = album?.Artists
|
||||
@@ -111,13 +122,16 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
}
|
||||
|
||||
AlbumArtistCache.Set(info.Path, albumArtistNames);
|
||||
var tagAlbum = tags?.Album;
|
||||
audio.Album = config.UseYandexAlbumName
|
||||
? album?.Title ?? info.Album
|
||||
: string.IsNullOrWhiteSpace(info.Album) ? album?.Title : info.Album;
|
||||
? 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) ?? info.Year;
|
||||
audio.ProductionYear = Mapping.ValidYear(album?.Year) ?? tags?.Year ?? info.Year;
|
||||
}
|
||||
|
||||
audio.PremiereDate = Mapping.ParseReleaseDate(album?.ReleaseDate);
|
||||
@@ -127,6 +141,8 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
: 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)
|
||||
@@ -159,18 +175,23 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
audio.ParentIndexNumber = disc;
|
||||
}
|
||||
|
||||
audio.SetProviderId(YandexProviderIds.Track, track.Id.ToString(CultureInfo.InvariantCulture));
|
||||
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, album.Id.ToString(CultureInfo.InvariantCulture));
|
||||
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, primaryArtist.Id.ToString(CultureInfo.InvariantCulture));
|
||||
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;
|
||||
@@ -220,28 +241,47 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||
|
||||
private async Task<TrackDto?> ResolveTrackAsync(SongInfo info, PluginConfiguration config, CancellationToken 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)
|
||||
{
|
||||
return byId;
|
||||
// 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(info, cancellationToken).ConfigureAwait(false);
|
||||
var artists = info.Artists.Count > 0 ? info.Artists : info.AlbumArtists;
|
||||
var durationMs = GetLocalDurationMs(info);
|
||||
var tracks = await SearchTracksAsync(title, artists, cancellationToken).ConfigureAwait(false);
|
||||
var match = MatchScoring.FindBestTrack(
|
||||
tracks,
|
||||
info.Name,
|
||||
title,
|
||||
artists,
|
||||
durationMs,
|
||||
config.MatchThreshold,
|
||||
config.DurationToleranceSeconds);
|
||||
config.DurationToleranceSeconds,
|
||||
album);
|
||||
if (match is null)
|
||||
{
|
||||
return null;
|
||||
@@ -251,18 +291,64 @@ public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>,
|
||||
return full ?? match.Value.Track;
|
||||
}
|
||||
|
||||
private async Task<List<TrackDto>> SearchTracksAsync(SongInfo info, CancellationToken cancellationToken)
|
||||
private Task<List<TrackDto>> SearchTracksAsync(SongInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
var artists = info.Artists.Count > 0 ? info.Artists : info.AlbumArtists;
|
||||
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))
|
||||
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))
|
||||
{
|
||||
tracks = await _client.SearchTracksAsync(info.Name, cancellationToken).ConfigureAwait(false);
|
||||
queries.Add($"{artist} {title}");
|
||||
}
|
||||
|
||||
return tracks;
|
||||
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)
|
||||
|
||||
@@ -224,7 +224,9 @@ public sealed class YandexMusicClient
|
||||
|
||||
var language = string.IsNullOrWhiteSpace(Config.Language) ? "ru" : Config.Language;
|
||||
var map = await GetGenresAsync(language, cancellationToken).ConfigureAwait(false);
|
||||
return map.TryGetValue(genreId, out var name) ? name : genreId;
|
||||
return map.TryGetValue(genreId, out var name)
|
||||
? name
|
||||
: Jellyfin.Plugin.YandexMusic.Providers.GenreNameMap.Normalize(genreId);
|
||||
}
|
||||
|
||||
private async Task<Dictionary<string, string>> GetGenresAsync(string language, 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
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: "Yandex Music"
|
||||
guid: "f3b9626b-da14-4cbf-8ad1-33b92cfa6656"
|
||||
version: "1.0.0.5"
|
||||
version: "1.0.0.12"
|
||||
targetAbi: "12.4.0.0"
|
||||
framework: "net10.0"
|
||||
overview: "Metadata for music from Yandex Music."
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
+5
-5
@@ -9,12 +9,12 @@
|
||||
"imageUrl": "",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.0.0.5",
|
||||
"changelog": "Add artist people links so the Artists tab works; maintenance task fills them for existing tracks.",
|
||||
"version": "1.0.0.12",
|
||||
"changelog": "Add genre normalization and an organize-into-albums task using hard 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.5.zip",
|
||||
"checksum": "3fa4bff9075e7e074991e8f47af9c26c",
|
||||
"timestamp": "2026-11-27T16:53:03Z"
|
||||
"sourceUrl": "https://git.midns.ru/1xDed/jellyfin-plugin-yandexmusic/raw/branch/main/dist/Jellyfin.Plugin.YandexMusic_1.0.0.12.zip",
|
||||
"checksum": "623c057061dec58cc175978180f57636",
|
||||
"timestamp": "2026-12-01T00:12:27Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
VERSION="1.0.0.5"
|
||||
VERSION="1.0.0.12"
|
||||
NAME="Jellyfin.Plugin.YandexMusic"
|
||||
PUBLISH_DIR="publish"
|
||||
ARTIFACTS_DIR="${ARTIFACTS_DIR:-artifacts}"
|
||||
|
||||
@@ -122,3 +122,25 @@ 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));
|
||||
|
||||
Console.WriteLine("== debug match ==");
|
||||
var dbg = await client.SearchTracksAsync("Pra(Killa'Gramm) LuckyProduction Больше ничего", CancellationToken.None);
|
||||
foreach (var t in dbg.Take(6))
|
||||
Console.WriteLine($"{t.Id} {t.Title} | {string.Join(",", t.Artists.Select(a=>a.Name))} | {t.DurationMs}");
|
||||
var hit2 = MatchScoring.FindBestTrack(dbg, "Больше ничего", new[]{"Pra(Killa'Gramm)","LuckyProduction"}, 190563, 0.72, 12);
|
||||
Console.WriteLine(hit2 is null ? "NO MATCH" : $"BEST {hit2.Value.Track.Id} {hit2.Value.Score:F3}");
|
||||
|
||||
Console.WriteLine("== debug polluted ==");
|
||||
var dbg2 = await client.SearchTracksAsync("polnalyubvi Pra(Killa'Gramm) LuckyProduction Больше ничего", CancellationToken.None);
|
||||
var hit3 = MatchScoring.FindBestTrack(dbg2, "Больше ничего", new[]{"polnalyubvi","Pra(Killa'Gramm)","LuckyProduction"}, 190563, 0.72, 12, "Больше ничего");
|
||||
Console.WriteLine(hit3 is null ? "NO MATCH" : $"BEST {hit3.Value.Track.Id} {hit3.Value.Track.Title} {hit3.Value.Score:F3}");
|
||||
|
||||
Console.WriteLine("== debug title-only ==");
|
||||
var dbg3 = await client.SearchTracksAsync("Больше ничего", CancellationToken.None);
|
||||
var hit4 = MatchScoring.FindBestTrack(dbg3, "Больше ничего", new[]{"polnalyubvi","Pra(Killa'Gramm)","LuckyProduction"}, 190563, 0.72, 12, "Больше ничего");
|
||||
foreach (var t in dbg3.Take(5)) Console.WriteLine($"{t.Id} {t.Title} | {string.Join(",",t.Artists.Select(a=>a.Name))} | {t.DurationMs} | {(t.Albums.FirstOrDefault()?.Title)}");
|
||||
Console.WriteLine(hit4 is null ? "NO MATCH" : $"BEST {hit4.Value.Track.Id} {hit4.Value.Score:F3}");
|
||||
|
||||
Console.WriteLine("== tag reader ==");
|
||||
var tt = Jellyfin.Plugin.YandexMusic.Providers.AudioTagReader.Read("/Users/kirill/Projects/jellyfin-local-test/media/Pra(Killa'Gramm), LuckyProduction - Больше ничего.mp3");
|
||||
Console.WriteLine(tt is null ? "TAGS FAILED" : $"{tt.Title} | {string.Join(";",tt.Artists)} | {tt.Album} | {tt.Year}");
|
||||
Reference in new issue
Block a user