1 Commits
Author SHA1 Message Date
1xDed 7106023d49 Release 1.0.0.12: genre normalization and album organization 2026-12-01 03:12:27 +03:00
11 changed files with 301 additions and 17 deletions

No files matched your search

@@ -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.11</Version>
<AssemblyVersion>1.0.0.11</AssemblyVersion>
<FileVersion>1.0.0.11</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>
@@ -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,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();
}
@@ -73,13 +73,12 @@ public class YandexMusicAudioCustomProvider : ICustomMetadataProvider<Audio>
}
}
if (GenreCache.TryGet(item.Path, out var genres) && genres.Length > 0)
var sourceGenres = GenreCache.TryGet(item.Path, out var cachedGenres) && cachedGenres.Length > 0
? cachedGenres
: item.Genres;
if (sourceGenres.Length > 0)
{
var distinctGenres = genres
.Select(g => g.Trim())
.Where(g => g.Length > 0)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
var distinctGenres = GenreNameMap.NormalizeAll(sourceGenres);
if (!distinctGenres.SequenceEqual(item.Genres, StringComparer.OrdinalIgnoreCase))
{
item.Genres = distinctGenres;
@@ -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)
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: "Yandex Music"
guid: "f3b9626b-da14-4cbf-8ad1-33b92cfa6656"
version: "1.0.0.11"
version: "1.0.0.12"
targetAbi: "12.4.0.0"
framework: "net10.0"
overview: "Metadata for music from Yandex Music."
+5 -5
View File
@@ -9,12 +9,12 @@
"imageUrl": "",
"versions": [
{
"version": "1.0.0.11",
"changelog": "Add admin endpoint to remove broken virtual folder entries.",
"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.11.zip",
"checksum": "c9ce5fe95bff06823e17b544d65bfe8f",
"timestamp": "2026-11-30T23:48:50Z"
"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
View File
@@ -3,7 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
VERSION="1.0.0.11"
VERSION="1.0.0.12"
NAME="Jellyfin.Plugin.YandexMusic"
PUBLISH_DIR="publish"
ARTIFACTS_DIR="${ARTIFACTS_DIR:-artifacts}"