Release 1.0.0.12: genre normalization and album organization
This commit is contained in:
1 parent
4bb222af8b
commit
7106023d49
11 files changed
+301
-17
No files matched your search
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user