Yandex Music metadata plugin for Jellyfin 12.4
This commit is contained in:
commit
c3dc901337
25 files changed
+3233
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
bin/
|
||||||
|
obj/
|
||||||
|
publish/
|
||||||
|
artifacts/
|
||||||
|
*.user
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Api;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plugin API used by the configuration page for Yandex OAuth device flow.
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("YandexMusic")]
|
||||||
|
[Authorize(Policy = "RequiresElevation")]
|
||||||
|
public class YandexMusicController : ControllerBase
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<string, DateTimeOffset> Sessions = new();
|
||||||
|
|
||||||
|
private readonly YandexMusicClient _client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicController"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public YandexMusicController(YandexMusicClient client)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts the device flow.</summary>
|
||||||
|
[HttpPost("DeviceCode")]
|
||||||
|
public async Task<ActionResult<DeviceCodeResult>> StartDeviceCode(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var code = await _client.RequestDeviceCodeAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
if (code is null)
|
||||||
|
{
|
||||||
|
return StatusCode(502, new { error = "Yandex OAuth did not return a device code." });
|
||||||
|
}
|
||||||
|
|
||||||
|
Sessions[code.DeviceCode] = DateTimeOffset.UtcNow.AddSeconds(code.ExpiresIn);
|
||||||
|
return new DeviceCodeResult(
|
||||||
|
code.DeviceCode,
|
||||||
|
code.UserCode,
|
||||||
|
code.VerificationUrl,
|
||||||
|
code.ExpiresIn,
|
||||||
|
Math.Max(2, code.Interval));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Polls the device flow once.</summary>
|
||||||
|
[HttpPost("DeviceCode/Poll")]
|
||||||
|
public async Task<ActionResult<DevicePollResult>> PollDeviceCode(
|
||||||
|
[FromBody] DevicePollRequest request,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.DeviceCode)
|
||||||
|
|| !Sessions.TryGetValue(request.DeviceCode, out var expires)
|
||||||
|
|| expires < DateTimeOffset.UtcNow)
|
||||||
|
{
|
||||||
|
return new DevicePollResult("expired", null, "Код истёк, запросите новый.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = await _client.PollDeviceTokenAsync(request.DeviceCode, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (token is null)
|
||||||
|
{
|
||||||
|
return new DevicePollResult("pending", null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(token.AccessToken))
|
||||||
|
{
|
||||||
|
return new DevicePollResult("error", null, token.ErrorDescription ?? token.Error ?? "Не удалось получить токен.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var config = Plugin.Instance!.Configuration;
|
||||||
|
config.Token = token.AccessToken!;
|
||||||
|
Plugin.Instance.UpdateConfiguration(config);
|
||||||
|
Sessions.TryRemove(request.DeviceCode, out _);
|
||||||
|
|
||||||
|
return new DevicePollResult("ok", token.AccessToken, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Returns connection status.</summary>
|
||||||
|
[HttpGet("Status")]
|
||||||
|
public async Task<ActionResult<StatusResult>> Status(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var connected = await _client.TestConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var config = Plugin.Instance?.Configuration;
|
||||||
|
return new StatusResult(
|
||||||
|
connected,
|
||||||
|
!string.IsNullOrWhiteSpace(config?.Token),
|
||||||
|
connected ? null : "api.music.yandex.net недоступен");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Clears the saved token.</summary>
|
||||||
|
[HttpPost("Logout")]
|
||||||
|
public ActionResult Logout()
|
||||||
|
{
|
||||||
|
var config = Plugin.Instance!.Configuration;
|
||||||
|
config.Token = string.Empty;
|
||||||
|
Plugin.Instance.UpdateConfiguration(config);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Device code returned to the config page.</summary>
|
||||||
|
public record DeviceCodeResult(
|
||||||
|
string DeviceCode,
|
||||||
|
string UserCode,
|
||||||
|
string VerificationUrl,
|
||||||
|
int ExpiresIn,
|
||||||
|
int Interval);
|
||||||
|
|
||||||
|
/// <summary>Device poll request.</summary>
|
||||||
|
public record DevicePollRequest(string DeviceCode);
|
||||||
|
|
||||||
|
/// <summary>Device poll result.</summary>
|
||||||
|
public record DevicePollResult(string Status, string? Token, string? Error);
|
||||||
|
|
||||||
|
/// <summary>Plugin status.</summary>
|
||||||
|
public record StatusResult(bool Connected, bool HasToken, string? Error);
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
using MediaBrowser.Model.Plugins;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plugin configuration.
|
||||||
|
/// </summary>
|
||||||
|
public class PluginConfiguration : BasePluginConfiguration
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the Yandex OAuth token. Optional, required only for lyrics.
|
||||||
|
/// </summary>
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the preferred language for genre names and artist descriptions.
|
||||||
|
/// </summary>
|
||||||
|
public string Language { get; set; } = "ru";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether song metadata is enabled.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSongMetadata { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether album metadata is enabled.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableAlbumMetadata { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether artist metadata is enabled.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableArtistMetadata { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether cover art is enabled.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableImages { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether lyrics are enabled.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableLyrics { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether the real album title from Yandex is written to the track's Album field.
|
||||||
|
/// When disabled (default), the existing album tag is kept.
|
||||||
|
/// </summary>
|
||||||
|
public bool UseYandexAlbumName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether the original release year from Yandex may replace the year tag.
|
||||||
|
/// </summary>
|
||||||
|
public bool UseYandexYear { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the minimum match score (0..1) required to accept a search result.
|
||||||
|
/// </summary>
|
||||||
|
public double MatchThreshold { get; set; } = 0.72;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the duration tolerance in seconds used while matching tracks.
|
||||||
|
/// </summary>
|
||||||
|
public int DurationToleranceSeconds { get; set; } = 12;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether genres from Yandex are written to items.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableGenres { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether labels are written as studios.
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableLabels { get; set; } = true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Yandex Music</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="YandexMusicConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
|
||||||
|
<div data-role="content">
|
||||||
|
<div class="content-primary">
|
||||||
|
<form id="YandexMusicConfigForm">
|
||||||
|
<div class="verticalSection">
|
||||||
|
<h2>Подключение к Яндекс.Музыке</h2>
|
||||||
|
<div class="fieldDescription">
|
||||||
|
Метаданные, обложки и жанры доступны без авторизации. Токен нужен только для текстов песен.
|
||||||
|
Токен хранится в конфигурации плагина на сервере.
|
||||||
|
</div>
|
||||||
|
<div class="inputContainer">
|
||||||
|
<label class="inputLabel inputLabelUnfocused" for="Token">OAuth-токен</label>
|
||||||
|
<input id="Token" name="Token" type="password" is="emby-input" autocomplete="off" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button id="LoginButton" is="emby-button" type="button" class="raised button-submit emby-button">
|
||||||
|
<span>Войти в Яндекс</span>
|
||||||
|
</button>
|
||||||
|
<button id="LogoutButton" is="emby-button" type="button" class="raised emby-button">
|
||||||
|
<span>Выйти</span>
|
||||||
|
</button>
|
||||||
|
<button id="CheckButton" is="emby-button" type="button" class="raised emby-button">
|
||||||
|
<span>Проверить соединение</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div id="DeviceBox" style="display:none;margin-top:1em" class="paperList">
|
||||||
|
<div class="fieldDescription">Откройте страницу и введите код:</div>
|
||||||
|
<p>
|
||||||
|
<a id="DeviceLink" href="https://ya.ru/device" target="_blank" rel="noopener noreferrer">https://ya.ru/device</a>
|
||||||
|
— код: <strong id="DeviceCode" style="font-size:1.4em;letter-spacing:.12em"></strong>
|
||||||
|
</p>
|
||||||
|
<div id="DeviceStatus" class="fieldDescription"></div>
|
||||||
|
</div>
|
||||||
|
<div id="StatusBox" class="fieldDescription" style="margin-top:.6em"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="verticalSection">
|
||||||
|
<h2>Что обогащать</h2>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableSongMetadata" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Треки (название, исполнитель, альбом, год, жанр, лейбл, номер трека)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableAlbumMetadata" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Альбомы</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableArtistMetadata" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Исполнители (биография, жанры, фото)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableImages" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Обложки</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableLyrics" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Тексты песен (нужен токен)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableGenres" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Жанры Яндекса</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="EnableLabels" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Лейблы (как студии)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="verticalSection">
|
||||||
|
<h2>Поведение</h2>
|
||||||
|
<div class="selectContainer">
|
||||||
|
<label class="selectLabel" for="Language">Язык жанров</label>
|
||||||
|
<select is="emby-select" id="Language" class="emby-select-withcolor emby-select">
|
||||||
|
<option value="ru">Русский</option>
|
||||||
|
<option value="en">English</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="UseYandexAlbumName" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Подставлять настоящее название альбома из Яндекса</span>
|
||||||
|
</label>
|
||||||
|
<div class="fieldDescription">
|
||||||
|
Если включить, отдельные файлы с одинаковым альбомом соберутся в альбомы после обновления метаданных.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||||
|
<label class="emby-checkbox-label">
|
||||||
|
<input id="UseYandexYear" type="checkbox" is="emby-checkbox" />
|
||||||
|
<span>Брать год из Яндекса</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="inputContainer">
|
||||||
|
<label class="inputLabel inputLabelUnfocused" for="MatchThreshold">Порог совпадения (0.5–0.95)</label>
|
||||||
|
<input id="MatchThreshold" type="number" is="emby-input" min="0.5" max="0.95" step="0.01" />
|
||||||
|
<div class="fieldDescription">Чем выше, тем меньше ложных совпадений и больше пропусков.</div>
|
||||||
|
</div>
|
||||||
|
<div class="inputContainer">
|
||||||
|
<label class="inputLabel inputLabelUnfocused" for="DurationToleranceSeconds">Допуск по длительности, сек</label>
|
||||||
|
<input id="DurationToleranceSeconds" type="number" is="emby-input" min="2" max="60" step="1" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
|
||||||
|
<span>Сохранить</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script type="text/javascript">
|
||||||
|
var YandexMusicConfig = {
|
||||||
|
pluginId: 'f3b9626b-da14-4cbf-8ad1-33b92cfa6656',
|
||||||
|
pollTimer: null
|
||||||
|
};
|
||||||
|
|
||||||
|
function adminPost(path, body) {
|
||||||
|
var options = {
|
||||||
|
type: 'POST',
|
||||||
|
url: ApiClient.getUrl('YandexMusic/' + path),
|
||||||
|
dataType: 'json'
|
||||||
|
};
|
||||||
|
if (body) {
|
||||||
|
options.data = JSON.stringify(body);
|
||||||
|
options.contentType = 'application/json';
|
||||||
|
}
|
||||||
|
return ApiClient.ajax(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setStatus(text) {
|
||||||
|
document.querySelector('#StatusBox').textContent = text || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopPolling() {
|
||||||
|
if (YandexMusicConfig.pollTimer) {
|
||||||
|
clearTimeout(YandexMusicConfig.pollTimer);
|
||||||
|
YandexMusicConfig.pollTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function pollDeviceCode(deviceCode, interval) {
|
||||||
|
YandexMusicConfig.pollTimer = setTimeout(function () {
|
||||||
|
adminPost('DeviceCode/Poll', { DeviceCode: deviceCode }).then(function (res) {
|
||||||
|
var status = document.querySelector('#DeviceStatus');
|
||||||
|
if (res.Status === 'pending') {
|
||||||
|
status.textContent = 'Ожидаем подтверждение…';
|
||||||
|
pollDeviceCode(deviceCode, interval);
|
||||||
|
} else if (res.Status === 'ok') {
|
||||||
|
document.querySelector('#Token').value = res.Token || '';
|
||||||
|
status.textContent = 'Готово, токен сохранён.';
|
||||||
|
setStatus('Токен получен.');
|
||||||
|
setTimeout(function () { document.querySelector('#DeviceBox').style.display = 'none'; }, 2500);
|
||||||
|
} else {
|
||||||
|
status.textContent = res.Error || 'Не удалось получить токен.';
|
||||||
|
}
|
||||||
|
}).catch(function () {
|
||||||
|
document.querySelector('#DeviceStatus').textContent = 'Ошибка запроса.';
|
||||||
|
});
|
||||||
|
}, Math.max(2, interval) * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelector('#YandexMusicConfigPage').addEventListener('pageshow', function () {
|
||||||
|
Dashboard.showLoadingMsg();
|
||||||
|
ApiClient.getPluginConfiguration(YandexMusicConfig.pluginId).then(function (config) {
|
||||||
|
document.querySelector('#Token').value = config.Token || '';
|
||||||
|
document.querySelector('#Language').value = config.Language || 'ru';
|
||||||
|
document.querySelector('#EnableSongMetadata').checked = config.EnableSongMetadata;
|
||||||
|
document.querySelector('#EnableAlbumMetadata').checked = config.EnableAlbumMetadata;
|
||||||
|
document.querySelector('#EnableArtistMetadata').checked = config.EnableArtistMetadata;
|
||||||
|
document.querySelector('#EnableImages').checked = config.EnableImages;
|
||||||
|
document.querySelector('#EnableLyrics').checked = config.EnableLyrics;
|
||||||
|
document.querySelector('#EnableGenres').checked = config.EnableGenres;
|
||||||
|
document.querySelector('#EnableLabels').checked = config.EnableLabels;
|
||||||
|
document.querySelector('#UseYandexAlbumName').checked = config.UseYandexAlbumName;
|
||||||
|
document.querySelector('#UseYandexYear').checked = config.UseYandexYear;
|
||||||
|
document.querySelector('#MatchThreshold').value = config.MatchThreshold;
|
||||||
|
document.querySelector('#DurationToleranceSeconds').value = config.DurationToleranceSeconds;
|
||||||
|
Dashboard.hideLoadingMsg();
|
||||||
|
ApiClient.ajax({
|
||||||
|
type: 'GET',
|
||||||
|
url: ApiClient.getUrl('YandexMusic/Status'),
|
||||||
|
dataType: 'json'
|
||||||
|
}).then(function (status) {
|
||||||
|
setStatus(status.Connected
|
||||||
|
? (status.HasToken ? 'API доступен, токен сохранён.' : 'API доступен, токен не задан (тексты песен выключены).')
|
||||||
|
: 'API недоступен: ' + (status.Error || ''));
|
||||||
|
}).catch(function () {
|
||||||
|
setStatus('Не удалось проверить состояние API.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelector('#YandexMusicConfigForm').addEventListener('submit', function (e) {
|
||||||
|
Dashboard.showLoadingMsg();
|
||||||
|
ApiClient.getPluginConfiguration(YandexMusicConfig.pluginId).then(function (config) {
|
||||||
|
config.Token = document.querySelector('#Token').value;
|
||||||
|
config.Language = document.querySelector('#Language').value;
|
||||||
|
config.EnableSongMetadata = document.querySelector('#EnableSongMetadata').checked;
|
||||||
|
config.EnableAlbumMetadata = document.querySelector('#EnableAlbumMetadata').checked;
|
||||||
|
config.EnableArtistMetadata = document.querySelector('#EnableArtistMetadata').checked;
|
||||||
|
config.EnableImages = document.querySelector('#EnableImages').checked;
|
||||||
|
config.EnableLyrics = document.querySelector('#EnableLyrics').checked;
|
||||||
|
config.EnableGenres = document.querySelector('#EnableGenres').checked;
|
||||||
|
config.EnableLabels = document.querySelector('#EnableLabels').checked;
|
||||||
|
config.UseYandexAlbumName = document.querySelector('#UseYandexAlbumName').checked;
|
||||||
|
config.UseYandexYear = document.querySelector('#UseYandexYear').checked;
|
||||||
|
config.MatchThreshold = parseFloat(document.querySelector('#MatchThreshold').value) || 0.72;
|
||||||
|
config.DurationToleranceSeconds = parseInt(document.querySelector('#DurationToleranceSeconds').value, 10) || 12;
|
||||||
|
ApiClient.updatePluginConfiguration(YandexMusicConfig.pluginId, config).then(function (result) {
|
||||||
|
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
e.preventDefault();
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelector('#LoginButton').addEventListener('click', function () {
|
||||||
|
stopPolling();
|
||||||
|
Dashboard.showLoadingMsg();
|
||||||
|
adminPost('DeviceCode').then(function (res) {
|
||||||
|
Dashboard.hideLoadingMsg();
|
||||||
|
document.querySelector('#DeviceBox').style.display = 'block';
|
||||||
|
document.querySelector('#DeviceCode').textContent = res.UserCode;
|
||||||
|
document.querySelector('#DeviceLink').href = res.VerificationUrl || 'https://ya.ru/device';
|
||||||
|
document.querySelector('#DeviceLink').textContent = res.VerificationUrl || 'https://ya.ru/device';
|
||||||
|
document.querySelector('#DeviceStatus').textContent = 'Ожидаем подтверждение…';
|
||||||
|
pollDeviceCode(res.DeviceCode, res.Interval);
|
||||||
|
}).catch(function () {
|
||||||
|
Dashboard.hideLoadingMsg();
|
||||||
|
setStatus('Не удалось начать вход в Яндекс.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelector('#LogoutButton').addEventListener('click', function () {
|
||||||
|
adminPost('Logout').then(function () {
|
||||||
|
document.querySelector('#Token').value = '';
|
||||||
|
setStatus('Токен удалён.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelector('#CheckButton').addEventListener('click', function () {
|
||||||
|
setStatus('Проверяем…');
|
||||||
|
ApiClient.ajax({
|
||||||
|
type: 'GET',
|
||||||
|
url: ApiClient.getUrl('YandexMusic/Status'),
|
||||||
|
dataType: 'json'
|
||||||
|
}).then(function (status) {
|
||||||
|
setStatus(status.Connected ? 'API доступен.' : 'API недоступен: ' + (status.Error || ''));
|
||||||
|
}).catch(function () {
|
||||||
|
setStatus('Ошибка проверки.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<RootNamespace>Jellyfin.Plugin.YandexMusic</RootNamespace>
|
||||||
|
<AssemblyName>Jellyfin.Plugin.YandexMusic</AssemblyName>
|
||||||
|
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<AnalysisMode>Default</AnalysisMode>
|
||||||
|
<NoWarn>$(NoWarn);CA1031;CA1848;CA2007;CA1305</NoWarn>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Jellyfin.Controller" Version="12.4.0">
|
||||||
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Jellyfin.Model" Version="12.4.0">
|
||||||
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="Configuration\configPage.html" />
|
||||||
|
<EmbeddedResource Include="Configuration\configPage.html" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Text normalization and fuzzy matching helpers.
|
||||||
|
/// </summary>
|
||||||
|
public static partial class TextMatch
|
||||||
|
{
|
||||||
|
/// <summary>Normalizes a title or artist name for comparison.</summary>
|
||||||
|
public static string Normalize(string? value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = value.ToLowerInvariant().Replace('ё', 'е');
|
||||||
|
text = ParenthesesRegex().Replace(text, " ");
|
||||||
|
text = BracketsRegex().Replace(text, " ");
|
||||||
|
var featIndex = text.IndexOf(" feat", StringComparison.Ordinal);
|
||||||
|
if (featIndex > 0)
|
||||||
|
{
|
||||||
|
text = text[..featIndex];
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder = new StringBuilder(text.Length);
|
||||||
|
var previousSpace = true;
|
||||||
|
foreach (var ch in text)
|
||||||
|
{
|
||||||
|
if (char.IsLetterOrDigit(ch))
|
||||||
|
{
|
||||||
|
builder.Append(ch);
|
||||||
|
previousSpace = false;
|
||||||
|
}
|
||||||
|
else if (!previousSpace)
|
||||||
|
{
|
||||||
|
builder.Append(' ');
|
||||||
|
previousSpace = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.ToString().Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Similarity in range 0..1 (best of edit distance ratio and token overlap).</summary>
|
||||||
|
public static double Similarity(string? left, string? right)
|
||||||
|
{
|
||||||
|
var a = Normalize(left);
|
||||||
|
var b = Normalize(right);
|
||||||
|
if (a.Length == 0 || b.Length == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.Equals(a, b, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.Max(LevenshteinRatio(a, b), TokenJaccard(a, b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Best similarity between two artist lists.</summary>
|
||||||
|
public static double ArtistSimilarity(IEnumerable<string?> left, IEnumerable<string?> right)
|
||||||
|
{
|
||||||
|
var leftParts = left.SelectMany(SplitArtists).ToArray();
|
||||||
|
var rightParts = right.SelectMany(SplitArtists).ToArray();
|
||||||
|
var best = 0d;
|
||||||
|
foreach (var a in leftParts)
|
||||||
|
{
|
||||||
|
foreach (var b in rightParts)
|
||||||
|
{
|
||||||
|
best = Math.Max(best, Similarity(a, b));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Splits a combined artist string ("A, B & C feat. D") into individual names.</summary>
|
||||||
|
public static IEnumerable<string> SplitArtists(string? value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = value.Replace(" & ", ", ", StringComparison.Ordinal)
|
||||||
|
.Replace(" and ", ", ", StringComparison.OrdinalIgnoreCase)
|
||||||
|
.Replace(" feat. ", ", ", StringComparison.OrdinalIgnoreCase)
|
||||||
|
.Replace(" feat ", ", ", StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
foreach (var part in text.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||||
|
{
|
||||||
|
if (part.Length > 0)
|
||||||
|
{
|
||||||
|
yield return part;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double LevenshteinRatio(string a, string b)
|
||||||
|
{
|
||||||
|
var distance = Levenshtein(a, b);
|
||||||
|
var max = Math.Max(a.Length, b.Length);
|
||||||
|
return max == 0 ? 1 : 1d - (double)distance / max;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Levenshtein(string a, string b)
|
||||||
|
{
|
||||||
|
if (a.Length == 0)
|
||||||
|
{
|
||||||
|
return b.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (b.Length == 0)
|
||||||
|
{
|
||||||
|
return a.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
var previous = new int[b.Length + 1];
|
||||||
|
var current = new int[b.Length + 1];
|
||||||
|
for (var j = 0; j <= b.Length; j++)
|
||||||
|
{
|
||||||
|
previous[j] = j;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 1; i <= a.Length; i++)
|
||||||
|
{
|
||||||
|
current[0] = i;
|
||||||
|
for (var j = 1; j <= b.Length; j++)
|
||||||
|
{
|
||||||
|
var cost = a[i - 1] == b[j - 1] ? 0 : 1;
|
||||||
|
current[j] = Math.Min(
|
||||||
|
Math.Min(current[j - 1] + 1, previous[j] + 1),
|
||||||
|
previous[j - 1] + cost);
|
||||||
|
}
|
||||||
|
|
||||||
|
(previous, current) = (current, previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
return previous[b.Length];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double TokenJaccard(string a, string b)
|
||||||
|
{
|
||||||
|
var left = a.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
var right = b.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
if (left.Length == 0 || right.Length == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var common = left.Intersect(right, StringComparer.Ordinal).Count();
|
||||||
|
var union = left.Union(right, StringComparer.Ordinal).Count();
|
||||||
|
return union == 0 ? 0 : (double)common / union;
|
||||||
|
}
|
||||||
|
|
||||||
|
[GeneratedRegex(@"\([^)]*\)", RegexOptions.CultureInvariant)]
|
||||||
|
private static partial Regex ParenthesesRegex();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"\[[^\]]*\]", RegexOptions.CultureInvariant)]
|
||||||
|
private static partial Regex BracketsRegex();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scores Yandex search results against local tags.
|
||||||
|
/// </summary>
|
||||||
|
public static class MatchScoring
|
||||||
|
{
|
||||||
|
/// <summary>Duration in milliseconds from Jellyfin ticks.</summary>
|
||||||
|
public static long TicksToMilliseconds(long? ticks)
|
||||||
|
=> ticks is null ? 0 : ticks.Value / TimeSpan.TicksPerMillisecond;
|
||||||
|
|
||||||
|
/// <summary>Finds the best matching track.</summary>
|
||||||
|
public static (TrackDto Track, double Score)? FindBestTrack(
|
||||||
|
IEnumerable<TrackDto> tracks,
|
||||||
|
string? title,
|
||||||
|
IReadOnlyList<string> artists,
|
||||||
|
long durationMs,
|
||||||
|
double threshold,
|
||||||
|
int toleranceSeconds)
|
||||||
|
{
|
||||||
|
(TrackDto Track, double Score)? best = null;
|
||||||
|
foreach (var track in tracks)
|
||||||
|
{
|
||||||
|
var titleScore = TextMatch.Similarity(title, track.Title);
|
||||||
|
var artistScore = TextMatch.ArtistSimilarity(
|
||||||
|
artists,
|
||||||
|
track.Artists.Select(a => a.Name));
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (best is null || score > best.Value.Score)
|
||||||
|
{
|
||||||
|
best = (track, score);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best is not null && best.Value.Score >= threshold ? best : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Finds the best matching album.</summary>
|
||||||
|
public static (AlbumDto Album, double Score)? FindBestAlbum(
|
||||||
|
IEnumerable<AlbumDto> albums,
|
||||||
|
string? title,
|
||||||
|
IReadOnlyList<string> artists,
|
||||||
|
int? year,
|
||||||
|
double threshold)
|
||||||
|
{
|
||||||
|
(AlbumDto Album, double Score)? best = null;
|
||||||
|
foreach (var album in albums)
|
||||||
|
{
|
||||||
|
var titleScore = TextMatch.Similarity(title, album.Title);
|
||||||
|
var artistScore = artists.Count == 0
|
||||||
|
? 1
|
||||||
|
: TextMatch.ArtistSimilarity(artists, album.Artists.Select(a => a.Name));
|
||||||
|
var yearScore = year is null || album.Year is null ? 0.5 : (year == album.Year ? 1 : 0);
|
||||||
|
var score = (0.55 * titleScore) + (0.3 * artistScore) + (0.15 * yearScore);
|
||||||
|
|
||||||
|
if (titleScore < 0.6)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (best is null || score > best.Value.Score)
|
||||||
|
{
|
||||||
|
best = (album, score);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best is not null && best.Value.Score >= threshold ? best : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Finds an artist whose name matches exactly (or nearly exactly).</summary>
|
||||||
|
public static ArtistDto? FindBestArtist(IEnumerable<ArtistDto> artists, string? name)
|
||||||
|
{
|
||||||
|
var normalized = TextMatch.Normalize(name);
|
||||||
|
if (normalized.Length == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
ArtistDto? best = null;
|
||||||
|
var bestScore = 0d;
|
||||||
|
foreach (var artist in artists)
|
||||||
|
{
|
||||||
|
var score = TextMatch.Similarity(normalized, artist.Name);
|
||||||
|
if (score > bestScore)
|
||||||
|
{
|
||||||
|
bestScore = score;
|
||||||
|
best = artist;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bestScore >= 0.86 ? best : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double? DurationScore(long localMs, long? remoteMs, int toleranceSeconds)
|
||||||
|
{
|
||||||
|
if (localMs <= 0 || remoteMs is null or <= 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var tolerance = Math.Max(2, toleranceSeconds) * 1000;
|
||||||
|
var difference = Math.Abs(localMs - remoteMs.Value);
|
||||||
|
if (difference <= tolerance / 2.0)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (difference <= tolerance)
|
||||||
|
{
|
||||||
|
return 0.85;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (difference <= tolerance * 2.0)
|
||||||
|
{
|
||||||
|
return 0.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using MediaBrowser.Common.Configuration;
|
||||||
|
using MediaBrowser.Common.Plugins;
|
||||||
|
using MediaBrowser.Model.Plugins;
|
||||||
|
using MediaBrowser.Model.Serialization;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Yandex Music metadata plugin.
|
||||||
|
/// </summary>
|
||||||
|
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="Plugin"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="applicationPaths">Application paths.</param>
|
||||||
|
/// <param name="xmlSerializer">XML serializer.</param>
|
||||||
|
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
|
||||||
|
: base(applicationPaths, xmlSerializer)
|
||||||
|
{
|
||||||
|
Instance = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override string Name => "Yandex Music";
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override Guid Id => Guid.Parse("f3b9626b-da14-4cbf-8ad1-33b92cfa6656");
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override string Description => "Metadata, cover art and lyrics from Yandex Music.";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the current plugin instance.
|
||||||
|
/// </summary>
|
||||||
|
public static Plugin? Instance { get; private set; }
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IEnumerable<PluginPageInfo> GetPages()
|
||||||
|
{
|
||||||
|
yield return new PluginPageInfo
|
||||||
|
{
|
||||||
|
Name = Name,
|
||||||
|
EmbeddedResourcePath = string.Format(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
"{0}.Configuration.configPage.html",
|
||||||
|
GetType().Namespace)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using MediaBrowser.Controller;
|
||||||
|
using MediaBrowser.Controller.Plugins;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers plugin services in the Jellyfin DI container.
|
||||||
|
/// </summary>
|
||||||
|
public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
|
||||||
|
{
|
||||||
|
serviceCollection.AddSingleton<YandexMusicClient>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>Creates image responses for search results.</summary>
|
||||||
|
internal static class ImageResponseFactory
|
||||||
|
{
|
||||||
|
/// <summary>Downloads an image and wraps it into an HTTP response.</summary>
|
||||||
|
public static async Task<HttpResponseMessage> FromUrlAsync(
|
||||||
|
YandexMusicClient client,
|
||||||
|
string url,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var bytes = await client.GetImageBytesAsync(url, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (bytes is null)
|
||||||
|
{
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
var content = new ByteArrayContent(bytes);
|
||||||
|
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using MediaBrowser.Model.Entities;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>Provider id keys used by this plugin.</summary>
|
||||||
|
public static class YandexProviderIds
|
||||||
|
{
|
||||||
|
/// <summary>Track id.</summary>
|
||||||
|
public const string Track = "YandexMusicTrack";
|
||||||
|
|
||||||
|
/// <summary>Album id.</summary>
|
||||||
|
public const string Album = "YandexMusicAlbum";
|
||||||
|
|
||||||
|
/// <summary>Artist id.</summary>
|
||||||
|
public const string Artist = "YandexMusicArtist";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shared mapping helpers.</summary>
|
||||||
|
public static class Mapping
|
||||||
|
{
|
||||||
|
/// <summary>Provider display name.</summary>
|
||||||
|
public const string ProviderName = "Yandex Music";
|
||||||
|
|
||||||
|
private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
|
||||||
|
/// <summary>Gets a provider id from lookup info.</summary>
|
||||||
|
public static long? GetId(IReadOnlyDictionary<string, string>? ids, string key)
|
||||||
|
{
|
||||||
|
if (ids is null || !ids.TryGetValue(key, out var value) || string.IsNullOrWhiteSpace(value))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) ? id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets a provider id from an item.</summary>
|
||||||
|
public static long? GetId(MediaBrowser.Controller.Entities.BaseItem item, string key)
|
||||||
|
{
|
||||||
|
var value = item.GetProviderId(key);
|
||||||
|
return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) ? id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Parses a Yandex release date.</summary>
|
||||||
|
public static DateTime? ParseReleaseDate(string? releaseDate)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(releaseDate))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (DateTime.TryParse(releaseDate, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var parsed))
|
||||||
|
{
|
||||||
|
return parsed.Year is >= 1900 and <= 2100 ? parsed : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Validates a release year.</summary>
|
||||||
|
public static int? ValidYear(int? year)
|
||||||
|
=> year is >= 1900 and <= 2100 ? year : null;
|
||||||
|
|
||||||
|
/// <summary>Maps a Yandex album genre to a Jellyfin genre name.</summary>
|
||||||
|
public static async Task<string[]> GenresAsync(
|
||||||
|
YandexMusicClient client,
|
||||||
|
string? albumGenre,
|
||||||
|
IEnumerable<string>? artistGenres,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (!Config.EnableGenres)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new List<string>();
|
||||||
|
var name = await client.GetGenreNameAsync(albumGenre, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!string.IsNullOrWhiteSpace(name))
|
||||||
|
{
|
||||||
|
result.Add(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var genre in (artistGenres ?? []).Take(4))
|
||||||
|
{
|
||||||
|
var artistGenre = await client.GetGenreNameAsync(genre, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!string.IsNullOrWhiteSpace(artistGenre)
|
||||||
|
&& !result.Contains(artistGenre, StringComparer.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
result.Add(artistGenre);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets label names.</summary>
|
||||||
|
public static string[] Labels(AlbumDto? album)
|
||||||
|
{
|
||||||
|
if (album is null || !Config.EnableLabels)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return album.Labels
|
||||||
|
.Select(l => l.Name)
|
||||||
|
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||||
|
.Select(n => n!)
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds a primary remote image when allowed.</summary>
|
||||||
|
public static void AddPrimaryImage<T>(
|
||||||
|
MediaBrowser.Controller.Providers.MetadataResult<T> result,
|
||||||
|
string? coverUri,
|
||||||
|
int size = 1000)
|
||||||
|
{
|
||||||
|
if (!Config.EnableImages)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var url = YandexMusicClient.BuildCoverUrl(coverUri, size);
|
||||||
|
if (!string.IsNullOrWhiteSpace(url))
|
||||||
|
{
|
||||||
|
result.RemoteImages.Add((url, MediaBrowser.Model.Entities.ImageType.Primary));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds a remote image of a given type.</summary>
|
||||||
|
public static void AddImage<T>(
|
||||||
|
MediaBrowser.Controller.Providers.MetadataResult<T> result,
|
||||||
|
string? coverUri,
|
||||||
|
MediaBrowser.Model.Entities.ImageType type,
|
||||||
|
int size = 1000)
|
||||||
|
{
|
||||||
|
if (!Config.EnableImages)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var url = YandexMusicClient.BuildCoverUrl(coverUri, size);
|
||||||
|
if (!string.IsNullOrWhiteSpace(url))
|
||||||
|
{
|
||||||
|
result.RemoteImages.Add((url, type));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using MediaBrowser.Controller.Entities.Audio;
|
||||||
|
using MediaBrowser.Controller.Providers;
|
||||||
|
using MediaBrowser.Model.Entities;
|
||||||
|
using MediaBrowser.Model.Providers;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Metadata provider for music albums.
|
||||||
|
/// </summary>
|
||||||
|
public class YandexMusicAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder
|
||||||
|
{
|
||||||
|
private readonly YandexMusicClient _client;
|
||||||
|
private readonly ILogger<YandexMusicAlbumProvider> _logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicAlbumProvider"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public YandexMusicAlbumProvider(YandexMusicClient client, ILogger<YandexMusicAlbumProvider> logger)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Name => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public int Order => 1;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = new MetadataResult<MusicAlbum> { Item = new MusicAlbum() };
|
||||||
|
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
if (!config.EnableAlbumMetadata)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var album = await ResolveAlbumAsync(info, config, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (album is null)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
var artists = album.Artists
|
||||||
|
.Select(a => a.Name)
|
||||||
|
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||||
|
.Select(n => n!)
|
||||||
|
.ToArray();
|
||||||
|
if (artists.Length == 0)
|
||||||
|
{
|
||||||
|
artists = info.AlbumArtists.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
var item = result.Item;
|
||||||
|
if (!string.IsNullOrWhiteSpace(album.Title))
|
||||||
|
{
|
||||||
|
item.Name = album.Title!;
|
||||||
|
}
|
||||||
|
|
||||||
|
item.Artists = artists;
|
||||||
|
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)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
var labels = Mapping.Labels(album);
|
||||||
|
if (labels.Length > 0)
|
||||||
|
{
|
||||||
|
item.Studios = labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
item.SetProviderId(YandexProviderIds.Album, album.Id.ToString(CultureInfo.InvariantCulture));
|
||||||
|
var primaryArtist = album.Artists.FirstOrDefault(a => a.Id > 0);
|
||||||
|
if (primaryArtist is not null)
|
||||||
|
{
|
||||||
|
item.SetProviderId(YandexProviderIds.Artist, primaryArtist.Id.ToString(CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
Mapping.AddPrimaryImage(result, album.CoverUri ?? album.OgImage, 1200);
|
||||||
|
result.HasMetadata = true;
|
||||||
|
result.QueriedById = Mapping.GetId(info.ProviderIds, YandexProviderIds.Album) is not null;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music failed to provide album metadata for {Name}", info.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var results = new List<RemoteSearchResult>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var albums = await SearchAlbumsAsync(searchInfo, cancellationToken).ConfigureAwait(false);
|
||||||
|
foreach (var album in albums)
|
||||||
|
{
|
||||||
|
results.Add(new RemoteSearchResult
|
||||||
|
{
|
||||||
|
Name = album.Title,
|
||||||
|
ProductionYear = album.Year,
|
||||||
|
Artists = album.Artists
|
||||||
|
.Select(a => new RemoteSearchResult { Name = a.Name })
|
||||||
|
.ToArray(),
|
||||||
|
ImageUrl = YandexMusicClient.BuildCoverUrl(album.CoverUri, 300),
|
||||||
|
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
[YandexProviderIds.Album] = album.Id.ToString(CultureInfo.InvariantCulture)
|
||||||
|
},
|
||||||
|
SearchProviderName = Name
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music album search failed for {Name}", searchInfo.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||||
|
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||||
|
|
||||||
|
private async Task<AlbumDto?> ResolveAlbumAsync(AlbumInfo info, PluginConfiguration config, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var albumId = Mapping.GetId(info.ProviderIds, YandexProviderIds.Album);
|
||||||
|
if (albumId is not null)
|
||||||
|
{
|
||||||
|
var byId = await _client.GetAlbumAsync(albumId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (byId is not null)
|
||||||
|
{
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var albums = await SearchAlbumsAsync(info, cancellationToken).ConfigureAwait(false);
|
||||||
|
var match = MatchScoring.FindBestAlbum(
|
||||||
|
albums,
|
||||||
|
info.Name,
|
||||||
|
info.AlbumArtists,
|
||||||
|
info.Year,
|
||||||
|
config.MatchThreshold);
|
||||||
|
return match?.Album;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<AlbumDto>> SearchAlbumsAsync(AlbumInfo info, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var artist = info.AlbumArtists.FirstOrDefault();
|
||||||
|
var query = string.IsNullOrWhiteSpace(artist) ? info.Name : $"{artist} {info.Name}";
|
||||||
|
var albums = await _client.SearchAlbumsAsync(query, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (albums.Count == 0 && !string.IsNullOrWhiteSpace(info.Name))
|
||||||
|
{
|
||||||
|
albums = await _client.SearchAlbumsAsync(info.Name, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return albums;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using MediaBrowser.Controller.Entities.Audio;
|
||||||
|
using MediaBrowser.Controller.Providers;
|
||||||
|
using MediaBrowser.Model.Entities;
|
||||||
|
using MediaBrowser.Model.Providers;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Metadata provider for music artists.
|
||||||
|
/// </summary>
|
||||||
|
public class YandexMusicArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo>, IHasOrder
|
||||||
|
{
|
||||||
|
private readonly YandexMusicClient _client;
|
||||||
|
private readonly ILogger<YandexMusicArtistProvider> _logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicArtistProvider"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public YandexMusicArtistProvider(YandexMusicClient client, ILogger<YandexMusicArtistProvider> logger)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Name => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public int Order => 1;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = new MetadataResult<MusicArtist> { Item = new MusicArtist() };
|
||||||
|
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
if (!config.EnableArtistMetadata)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var artist = await ResolveArtistAsync(info, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (artist is null)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
var details = await _client.GetArtistInfoAsync(artist.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
var item = result.Item;
|
||||||
|
item.Name = artist.Name ?? info.Name;
|
||||||
|
item.Genres = await Mapping.GenresAsync(_client, null, artist.Genres, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(details?.Description))
|
||||||
|
{
|
||||||
|
item.Overview = details!.Description;
|
||||||
|
}
|
||||||
|
else if (!string.IsNullOrWhiteSpace(artist.Description))
|
||||||
|
{
|
||||||
|
item.Overview = artist.Description;
|
||||||
|
}
|
||||||
|
|
||||||
|
item.SetProviderId(YandexProviderIds.Artist, artist.Id.ToString(CultureInfo.InvariantCulture));
|
||||||
|
|
||||||
|
var covers = new List<string?>();
|
||||||
|
if (details?.Covers is { Count: > 0 })
|
||||||
|
{
|
||||||
|
covers.AddRange(details.Covers.Select(c => c.Uri));
|
||||||
|
}
|
||||||
|
|
||||||
|
covers.Add(artist.Cover?.Uri);
|
||||||
|
covers.Add(artist.OgImage);
|
||||||
|
covers = covers.Where(c => !string.IsNullOrWhiteSpace(c)).Distinct(StringComparer.Ordinal).ToList();
|
||||||
|
|
||||||
|
if (covers.Count > 0)
|
||||||
|
{
|
||||||
|
Mapping.AddPrimaryImage(result, covers[0], 1200);
|
||||||
|
foreach (var cover in covers.Skip(1).Take(4))
|
||||||
|
{
|
||||||
|
Mapping.AddImage(result, cover, ImageType.Backdrop, 1920);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.HasMetadata = true;
|
||||||
|
result.QueriedById = Mapping.GetId(info.ProviderIds, YandexProviderIds.Artist) is not null;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music failed to provide artist metadata for {Name}", info.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var results = new List<RemoteSearchResult>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var artists = await _client.SearchArtistsAsync(searchInfo.Name ?? string.Empty, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
foreach (var artist in artists)
|
||||||
|
{
|
||||||
|
results.Add(new RemoteSearchResult
|
||||||
|
{
|
||||||
|
Name = artist.Name,
|
||||||
|
ImageUrl = YandexMusicClient.BuildCoverUrl(artist.Cover?.Uri ?? artist.OgImage, 300),
|
||||||
|
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
[YandexProviderIds.Artist] = artist.Id.ToString(CultureInfo.InvariantCulture)
|
||||||
|
},
|
||||||
|
SearchProviderName = Name
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music artist search failed for {Name}", searchInfo.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||||
|
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||||
|
|
||||||
|
private async Task<ArtistDto?> ResolveArtistAsync(ArtistInfo info, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var artistId = Mapping.GetId(info.ProviderIds, YandexProviderIds.Artist);
|
||||||
|
if (artistId is not null)
|
||||||
|
{
|
||||||
|
var byId = await _client.GetArtistAsync(artistId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (byId is not null)
|
||||||
|
{
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var artists = await _client.SearchArtistsAsync(info.Name ?? string.Empty, cancellationToken).ConfigureAwait(false);
|
||||||
|
var match = MatchScoring.FindBestArtist(artists, info.Name);
|
||||||
|
if (match is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _client.GetArtistAsync(match.Id, cancellationToken).ConfigureAwait(false) ?? match;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
using MediaBrowser.Controller.Entities;
|
||||||
|
using MediaBrowser.Controller.Entities.Audio;
|
||||||
|
using MediaBrowser.Controller.Providers;
|
||||||
|
using MediaBrowser.Model.Entities;
|
||||||
|
using MediaBrowser.Model.Providers;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>Track external id.</summary>
|
||||||
|
public class YandexMusicTrackExternalId : IExternalId
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string ProviderName => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Key => YandexProviderIds.Track;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public ExternalIdMediaType? Type => ExternalIdMediaType.Track;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(IHasProviderIds item) => item is Audio;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Album external id.</summary>
|
||||||
|
public class YandexMusicAlbumExternalId : IExternalId
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string ProviderName => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Key => YandexProviderIds.Album;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public ExternalIdMediaType? Type => ExternalIdMediaType.Album;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(IHasProviderIds item) => item is MusicAlbum;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Artist external id.</summary>
|
||||||
|
public class YandexMusicArtistExternalId : IExternalId
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string ProviderName => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Key => YandexProviderIds.Artist;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public ExternalIdMediaType? Type => ExternalIdMediaType.Artist;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(IHasProviderIds item) => item is MusicArtist;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Links to music.yandex.ru on item pages.</summary>
|
||||||
|
public class YandexMusicExternalUrlProvider : IExternalUrlProvider
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Name => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IEnumerable<string> GetExternalUrls(BaseItem item)
|
||||||
|
{
|
||||||
|
switch (item)
|
||||||
|
{
|
||||||
|
case MusicAlbum album:
|
||||||
|
var albumId = album.GetProviderId(YandexProviderIds.Album);
|
||||||
|
if (!string.IsNullOrEmpty(albumId))
|
||||||
|
{
|
||||||
|
yield return $"https://music.yandex.ru/album/{albumId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MusicArtist artist:
|
||||||
|
var artistId = artist.GetProviderId(YandexProviderIds.Artist);
|
||||||
|
if (!string.IsNullOrEmpty(artistId))
|
||||||
|
{
|
||||||
|
yield return $"https://music.yandex.ru/artist/{artistId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Audio audio:
|
||||||
|
var trackId = audio.GetProviderId(YandexProviderIds.Track);
|
||||||
|
var trackAlbumId = audio.GetProviderId(YandexProviderIds.Album);
|
||||||
|
if (!string.IsNullOrEmpty(trackId))
|
||||||
|
{
|
||||||
|
yield return string.IsNullOrEmpty(trackAlbumId)
|
||||||
|
? $"https://music.yandex.ru/track/{trackId}"
|
||||||
|
: $"https://music.yandex.ru/album/{trackAlbumId}/track/{trackId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using MediaBrowser.Controller.Entities;
|
||||||
|
using MediaBrowser.Controller.Entities.Audio;
|
||||||
|
using MediaBrowser.Controller.Providers;
|
||||||
|
using MediaBrowser.Model.Entities;
|
||||||
|
using MediaBrowser.Model.Providers;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cover art provider.
|
||||||
|
/// </summary>
|
||||||
|
public class YandexMusicImageProvider : IRemoteImageProvider, IHasOrder
|
||||||
|
{
|
||||||
|
private readonly YandexMusicClient _client;
|
||||||
|
private readonly ILogger<YandexMusicImageProvider> _logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicImageProvider"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public YandexMusicImageProvider(YandexMusicClient client, ILogger<YandexMusicImageProvider> logger)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Name => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public int Order => 1;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public bool Supports(BaseItem item) => item is Audio or MusicAlbum or MusicArtist;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
|
||||||
|
=> item is MusicArtist ? [ImageType.Primary, ImageType.Backdrop] : [ImageType.Primary];
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
if (!config.EnableImages)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var covers = item switch
|
||||||
|
{
|
||||||
|
Audio audio => await GetAudioCoversAsync(audio, config, cancellationToken).ConfigureAwait(false),
|
||||||
|
MusicAlbum album => await GetAlbumCoversAsync(album, config, cancellationToken).ConfigureAwait(false),
|
||||||
|
MusicArtist artist => await GetArtistCoversAsync(artist, cancellationToken).ConfigureAwait(false),
|
||||||
|
_ => new List<(string Url, ImageType Type, int Size)>()
|
||||||
|
};
|
||||||
|
|
||||||
|
return covers.Select(c => new RemoteImageInfo
|
||||||
|
{
|
||||||
|
ProviderName = Name,
|
||||||
|
Url = c.Url,
|
||||||
|
Type = c.Type,
|
||||||
|
Width = c.Size,
|
||||||
|
Height = c.Size
|
||||||
|
}).ToArray();
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music failed to find images for {Name}", item.Name);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var bytes = await _client.GetImageBytesAsync(url, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (bytes is null)
|
||||||
|
{
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
var content = new ByteArrayContent(bytes);
|
||||||
|
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||||||
|
return new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<(string Url, ImageType Type, int Size)>> GetAudioCoversAsync(
|
||||||
|
Audio audio,
|
||||||
|
PluginConfiguration config,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var trackId = Mapping.GetId(audio, YandexProviderIds.Track);
|
||||||
|
if (trackId is not null)
|
||||||
|
{
|
||||||
|
var track = await _client.GetTrackAsync(trackId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (track is not null)
|
||||||
|
{
|
||||||
|
return Collect(track.CoverUri ?? track.Albums.FirstOrDefault()?.CoverUri, ImageType.Primary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var albumId = Mapping.GetId(audio, YandexProviderIds.Album);
|
||||||
|
if (albumId is not null)
|
||||||
|
{
|
||||||
|
var album = await _client.GetAlbumAsync(albumId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (album is not null)
|
||||||
|
{
|
||||||
|
return Collect(album.CoverUri, ImageType.Primary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var tracks = await _client.SearchTracksAsync($"{audio.Artists.FirstOrDefault()} {audio.Name}", cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
var match = MatchScoring.FindBestTrack(
|
||||||
|
tracks,
|
||||||
|
audio.Name,
|
||||||
|
audio.Artists,
|
||||||
|
MatchScoring.TicksToMilliseconds(audio.RunTimeTicks),
|
||||||
|
config.MatchThreshold,
|
||||||
|
config.DurationToleranceSeconds);
|
||||||
|
return match is null
|
||||||
|
? []
|
||||||
|
: Collect(match.Value.Track.CoverUri ?? match.Value.Track.Albums.FirstOrDefault()?.CoverUri, ImageType.Primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<(string Url, ImageType Type, int Size)>> GetAlbumCoversAsync(
|
||||||
|
MusicAlbum album,
|
||||||
|
PluginConfiguration config,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var albumId = Mapping.GetId(album, YandexProviderIds.Album);
|
||||||
|
if (albumId is not null)
|
||||||
|
{
|
||||||
|
var byId = await _client.GetAlbumAsync(albumId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (byId is not null)
|
||||||
|
{
|
||||||
|
return Collect(byId.CoverUri, ImageType.Primary, 1200);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var artist = album.AlbumArtists.FirstOrDefault();
|
||||||
|
var query = string.IsNullOrWhiteSpace(artist) ? album.Name : $"{artist} {album.Name}";
|
||||||
|
var albums = await _client.SearchAlbumsAsync(query, cancellationToken).ConfigureAwait(false);
|
||||||
|
var match = MatchScoring.FindBestAlbum(
|
||||||
|
albums,
|
||||||
|
album.Name,
|
||||||
|
album.AlbumArtists,
|
||||||
|
album.ProductionYear,
|
||||||
|
config.MatchThreshold);
|
||||||
|
return match is null
|
||||||
|
? []
|
||||||
|
: Collect(match.Value.Album.CoverUri, ImageType.Primary, 1200);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<(string Url, ImageType Type, int Size)>> GetArtistCoversAsync(
|
||||||
|
MusicArtist artist,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var artistId = Mapping.GetId(artist, YandexProviderIds.Artist);
|
||||||
|
ArtistDto? dto = null;
|
||||||
|
if (artistId is not null)
|
||||||
|
{
|
||||||
|
dto = await _client.GetArtistAsync(artistId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var artists = await _client.SearchArtistsAsync(artist.Name, cancellationToken).ConfigureAwait(false);
|
||||||
|
dto = MatchScoring.FindBestArtist(artists, artist.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto is null)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var covers = new List<(string Url, ImageType Type, int Size)>();
|
||||||
|
var details = await _client.GetArtistInfoAsync(dto.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
var uris = new List<string?>();
|
||||||
|
if (details?.Covers is { Count: > 0 })
|
||||||
|
{
|
||||||
|
uris.AddRange(details.Covers.Select(c => c.Uri));
|
||||||
|
}
|
||||||
|
|
||||||
|
uris.Add(dto.Cover?.Uri);
|
||||||
|
uris.Add(dto.OgImage);
|
||||||
|
|
||||||
|
var primaryAdded = false;
|
||||||
|
foreach (var uri in uris.Where(u => !string.IsNullOrWhiteSpace(u)).Distinct(StringComparer.Ordinal))
|
||||||
|
{
|
||||||
|
var url = YandexMusicClient.BuildCoverUrl(uri, primaryAdded ? 1920 : 1200);
|
||||||
|
if (url is null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
covers.Add((url, primaryAdded ? ImageType.Backdrop : ImageType.Primary, primaryAdded ? 1920 : 1200));
|
||||||
|
primaryAdded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return covers;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<(string Url, ImageType Type, int Size)> Collect(string? coverUri, ImageType type, int size = 1000)
|
||||||
|
{
|
||||||
|
var url = YandexMusicClient.BuildCoverUrl(coverUri, size);
|
||||||
|
return url is null ? [] : [(url, type, size)];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using MediaBrowser.Controller.Lyrics;
|
||||||
|
using MediaBrowser.Controller.Providers;
|
||||||
|
using MediaBrowser.Model.Lyrics;
|
||||||
|
using MediaBrowser.Model.Providers;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Lyrics provider backed by Yandex Music (requires an OAuth token).
|
||||||
|
/// </summary>
|
||||||
|
public class YandexMusicLyricProvider : ILyricProvider, IHasOrder
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<long, (string Text, string Format, DateTime At)> Cache = new();
|
||||||
|
|
||||||
|
private readonly YandexMusicClient _client;
|
||||||
|
private readonly ILogger<YandexMusicLyricProvider> _logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicLyricProvider"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public YandexMusicLyricProvider(YandexMusicClient client, ILogger<YandexMusicLyricProvider> logger)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Name => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public int Order => 1;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IEnumerable<RemoteLyricInfo>> SearchAsync(LyricSearchRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
if (!config.EnableLyrics || !YandexMusicClient.HasToken)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var trackId = Mapping.GetId(request.ProviderIds, YandexProviderIds.Track);
|
||||||
|
TrackDto? track = null;
|
||||||
|
if (trackId is not null)
|
||||||
|
{
|
||||||
|
track = await _client.GetTrackAsync(trackId.Value, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (track is null)
|
||||||
|
{
|
||||||
|
var artist = request.ArtistNames?.FirstOrDefault() ?? request.AlbumArtistsNames?.FirstOrDefault();
|
||||||
|
var query = string.IsNullOrWhiteSpace(artist)
|
||||||
|
? request.SongName
|
||||||
|
: $"{artist} {request.SongName}";
|
||||||
|
var tracks = await _client.SearchTracksAsync(query ?? string.Empty, cancellationToken).ConfigureAwait(false);
|
||||||
|
var durationMs = request.Duration is null ? 0 : request.Duration.Value / TimeSpan.TicksPerMillisecond;
|
||||||
|
var artists = (IReadOnlyList<string>?)request.ArtistNames
|
||||||
|
?? request.AlbumArtistsNames
|
||||||
|
?? Array.Empty<string>();
|
||||||
|
var match = MatchScoring.FindBestTrack(
|
||||||
|
tracks,
|
||||||
|
request.SongName,
|
||||||
|
artists,
|
||||||
|
durationMs,
|
||||||
|
config.MatchThreshold,
|
||||||
|
config.DurationToleranceSeconds);
|
||||||
|
track = match?.Track;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (track is null)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (track.LyricsAvailable is false && track.LyricsInfo is { HasLyrics: false })
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var lyrics = await GetLyricsTextAsync(track.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (lyrics is null)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var (text, format) = lyrics.Value;
|
||||||
|
return
|
||||||
|
[
|
||||||
|
new RemoteLyricInfo
|
||||||
|
{
|
||||||
|
Id = track.Id.ToString(CultureInfo.InvariantCulture),
|
||||||
|
ProviderName = Name,
|
||||||
|
Metadata = new LyricMetadata
|
||||||
|
{
|
||||||
|
Title = track.Title,
|
||||||
|
Artist = string.Join(", ", track.Artists.Select(a => a.Name).Where(n => !string.IsNullOrWhiteSpace(n))),
|
||||||
|
Album = track.Albums.FirstOrDefault()?.Title,
|
||||||
|
Length = request.Duration,
|
||||||
|
IsSynced = string.Equals(format, "lrc", StringComparison.OrdinalIgnoreCase)
|
||||||
|
},
|
||||||
|
Lyrics = new LyricResponse
|
||||||
|
{
|
||||||
|
Stream = new MemoryStream(Encoding.UTF8.GetBytes(text)),
|
||||||
|
Format = format
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music lyrics search failed for {Song}", request.SongName);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<LyricResponse?> GetLyricsAsync(string id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (!long.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var trackId))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var lyrics = await GetLyricsTextAsync(trackId, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (lyrics is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LyricResponse
|
||||||
|
{
|
||||||
|
Stream = new MemoryStream(Encoding.UTF8.GetBytes(lyrics.Value.Text)),
|
||||||
|
Format = lyrics.Value.Format
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<(string Text, string Format)?> GetLyricsTextAsync(long trackId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (Cache.TryGetValue(trackId, out var cached) && DateTime.UtcNow - cached.At < TimeSpan.FromHours(2))
|
||||||
|
{
|
||||||
|
return (cached.Text, cached.Format);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var format in new[] { "LRC", "TEXT" })
|
||||||
|
{
|
||||||
|
var text = await _client.GetLyricsTextAsync(trackId, format, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
var normalizedFormat = format == "LRC" ? "lrc" : "txt";
|
||||||
|
Cache[trackId] = (text, normalizedFormat, DateTime.UtcNow);
|
||||||
|
return (text, normalizedFormat);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using MediaBrowser.Controller.Entities.Audio;
|
||||||
|
using MediaBrowser.Controller.Library;
|
||||||
|
using MediaBrowser.Controller.Providers;
|
||||||
|
using MediaBrowser.Model.Entities;
|
||||||
|
using MediaBrowser.Model.Providers;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Providers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Metadata provider for individual songs (Audio items).
|
||||||
|
/// </summary>
|
||||||
|
public class YandexMusicSongProvider : IRemoteMetadataProvider<Audio, SongInfo>, IHasOrder
|
||||||
|
{
|
||||||
|
private readonly YandexMusicClient _client;
|
||||||
|
private readonly ILibraryManager _libraryManager;
|
||||||
|
private readonly ILogger<YandexMusicSongProvider> _logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicSongProvider"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public YandexMusicSongProvider(
|
||||||
|
YandexMusicClient client,
|
||||||
|
ILibraryManager libraryManager,
|
||||||
|
ILogger<YandexMusicSongProvider> logger)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_libraryManager = libraryManager;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Name => Mapping.ProviderName;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public int Order => 1;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<MetadataResult<Audio>> GetMetadata(SongInfo info, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var result = new MetadataResult<Audio> { Item = new Audio(), QueriedById = false };
|
||||||
|
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
if (!config.EnableSongMetadata)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var track = await ResolveTrackAsync(info, config, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (track is null)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
var album = track.Albums.FirstOrDefault();
|
||||||
|
if (album is not null)
|
||||||
|
{
|
||||||
|
album = await _client.GetAlbumAsync(album.Id, cancellationToken).ConfigureAwait(false) ?? album;
|
||||||
|
}
|
||||||
|
|
||||||
|
var artistNames = track.Artists
|
||||||
|
.Select(a => a.Name)
|
||||||
|
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||||
|
.Select(n => n!)
|
||||||
|
.ToArray();
|
||||||
|
if (artistNames.Length == 0)
|
||||||
|
{
|
||||||
|
artistNames = info.Artists.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
var albumArtistNames = album?.Artists
|
||||||
|
.Select(a => a.Name)
|
||||||
|
.Where(n => !string.IsNullOrWhiteSpace(n))
|
||||||
|
.Select(n => n!)
|
||||||
|
.ToArray() ?? [];
|
||||||
|
if (albumArtistNames.Length == 0)
|
||||||
|
{
|
||||||
|
albumArtistNames = artistNames;
|
||||||
|
}
|
||||||
|
|
||||||
|
var audio = result.Item;
|
||||||
|
if (!string.IsNullOrWhiteSpace(track.Title))
|
||||||
|
{
|
||||||
|
audio.Name = track.Title!;
|
||||||
|
}
|
||||||
|
|
||||||
|
audio.Artists = artistNames;
|
||||||
|
audio.AlbumArtists = albumArtistNames;
|
||||||
|
audio.Album = config.UseYandexAlbumName
|
||||||
|
? album?.Title ?? info.Album
|
||||||
|
: string.IsNullOrWhiteSpace(info.Album) ? album?.Title : info.Album;
|
||||||
|
|
||||||
|
if (config.UseYandexYear)
|
||||||
|
{
|
||||||
|
audio.ProductionYear = Mapping.ValidYear(album?.Year) ?? info.Year;
|
||||||
|
}
|
||||||
|
|
||||||
|
audio.PremiereDate = Mapping.ParseReleaseDate(album?.ReleaseDate);
|
||||||
|
audio.Genres = await Mapping.GenresAsync(_client, album?.Genre, null, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
var labels = Mapping.Labels(album);
|
||||||
|
if (labels.Length == 0 && !string.IsNullOrWhiteSpace(track.Major?.Name))
|
||||||
|
{
|
||||||
|
labels = [track.Major!.Name!];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (labels.Length > 0)
|
||||||
|
{
|
||||||
|
audio.Studios = labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
var (index, disc) = FindPosition(album, track.Id);
|
||||||
|
if (index is not null)
|
||||||
|
{
|
||||||
|
audio.IndexNumber = index;
|
||||||
|
audio.ParentIndexNumber = disc;
|
||||||
|
}
|
||||||
|
|
||||||
|
audio.SetProviderId(YandexProviderIds.Track, track.Id.ToString(CultureInfo.InvariantCulture));
|
||||||
|
if (album is not null)
|
||||||
|
{
|
||||||
|
audio.SetProviderId(YandexProviderIds.Album, album.Id.ToString(CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
var primaryArtist = track.Artists.FirstOrDefault(a => a.Id > 0);
|
||||||
|
if (primaryArtist is not null)
|
||||||
|
{
|
||||||
|
audio.SetProviderId(YandexProviderIds.Artist, primaryArtist.Id.ToString(CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
Mapping.AddPrimaryImage(result, track.CoverUri ?? album?.CoverUri);
|
||||||
|
result.HasMetadata = true;
|
||||||
|
result.QueriedById = Mapping.GetId(info.ProviderIds, YandexProviderIds.Track) is not null;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music failed to provide metadata for {Name}", info.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SongInfo searchInfo, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
var results = new List<RemoteSearchResult>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var tracks = await SearchTracksAsync(searchInfo, cancellationToken).ConfigureAwait(false);
|
||||||
|
foreach (var track in tracks)
|
||||||
|
{
|
||||||
|
results.Add(new RemoteSearchResult
|
||||||
|
{
|
||||||
|
Name = track.Title,
|
||||||
|
Artists = track.Artists
|
||||||
|
.Select(a => new RemoteSearchResult { Name = a.Name })
|
||||||
|
.ToArray(),
|
||||||
|
ImageUrl = YandexMusicClient.BuildCoverUrl(track.CoverUri, 300),
|
||||||
|
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
[YandexProviderIds.Track] = track.Id.ToString(CultureInfo.InvariantCulture)
|
||||||
|
},
|
||||||
|
SearchProviderName = Name
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music search failed for {Name}", searchInfo.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
|
||||||
|
=> ImageResponseFactory.FromUrlAsync(_client, url, cancellationToken);
|
||||||
|
|
||||||
|
private async Task<TrackDto?> ResolveTrackAsync(SongInfo info, PluginConfiguration config, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var tracks = await SearchTracksAsync(info, cancellationToken).ConfigureAwait(false);
|
||||||
|
var artists = info.Artists.Count > 0 ? info.Artists : info.AlbumArtists;
|
||||||
|
var durationMs = GetLocalDurationMs(info);
|
||||||
|
var match = MatchScoring.FindBestTrack(
|
||||||
|
tracks,
|
||||||
|
info.Name,
|
||||||
|
artists,
|
||||||
|
durationMs,
|
||||||
|
config.MatchThreshold,
|
||||||
|
config.DurationToleranceSeconds);
|
||||||
|
if (match is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var full = await _client.GetTrackAsync(match.Value.Track.Id, cancellationToken).ConfigureAwait(false);
|
||||||
|
return full ?? match.Value.Track;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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))
|
||||||
|
{
|
||||||
|
tracks = await _client.SearchTracksAsync(info.Name, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return tracks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long GetLocalDurationMs(SongInfo info)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(info.Path))
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var item = _libraryManager.FindByPath(info.Path, false);
|
||||||
|
return item is Audio audio ? MatchScoring.TicksToMilliseconds(audio.RunTimeTicks) : 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogDebug(ex, "Failed to resolve local audio item for {Path}", info.Path);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int? Index, int? Disc) FindPosition(AlbumDto? album, long trackId)
|
||||||
|
{
|
||||||
|
if (album is null || album.Volumes.Count == 0)
|
||||||
|
{
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var disc = 0; disc < album.Volumes.Count; disc++)
|
||||||
|
{
|
||||||
|
var index = album.Volumes[disc].IndexOf(trackId);
|
||||||
|
if (index >= 0)
|
||||||
|
{
|
||||||
|
return (index + 1, disc + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads numbers that Yandex sometimes returns as strings.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class FlexibleLongConverter : JsonConverter<long>
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
if (reader.TokenType == JsonTokenType.Number)
|
||||||
|
{
|
||||||
|
return reader.GetInt64();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reader.TokenType == JsonTokenType.String)
|
||||||
|
{
|
||||||
|
var value = reader.GetString();
|
||||||
|
return long.TryParse(value, out var result) ? result : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
|
||||||
|
=> writer.WriteNumberValue(value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Yandex returns album labels either as objects or as plain strings depending on the endpoint.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LabelListConverter : JsonConverter<List<LabelDto>>
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override List<LabelDto> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
var result = new List<LabelDto>();
|
||||||
|
if (reader.TokenType == JsonTokenType.Null)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reader.TokenType != JsonTokenType.StartArray)
|
||||||
|
{
|
||||||
|
throw new JsonException("Expected an array of labels.");
|
||||||
|
}
|
||||||
|
|
||||||
|
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
|
||||||
|
{
|
||||||
|
if (reader.TokenType == JsonTokenType.String)
|
||||||
|
{
|
||||||
|
result.Add(new LabelDto { Name = reader.GetString() });
|
||||||
|
}
|
||||||
|
else if (reader.TokenType == JsonTokenType.StartObject)
|
||||||
|
{
|
||||||
|
var label = JsonSerializer.Deserialize<LabelDto>(ref reader, options);
|
||||||
|
if (label is not null)
|
||||||
|
{
|
||||||
|
result.Add(label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public override void Write(Utf8JsonWriter writer, List<LabelDto> value, JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
writer.WriteStartArray();
|
||||||
|
foreach (var label in value)
|
||||||
|
{
|
||||||
|
writer.WriteStartObject();
|
||||||
|
writer.WriteNumber("id", label.Id);
|
||||||
|
writer.WriteString("name", label.Name);
|
||||||
|
writer.WriteEndObject();
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WriteEndArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
/// <summary>Generic Yandex API envelope.</summary>
|
||||||
|
public sealed class YandexResponse<T>
|
||||||
|
{
|
||||||
|
[JsonPropertyName("result")]
|
||||||
|
public T? Result { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("error")]
|
||||||
|
public YandexError? Error { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Yandex API error.</summary>
|
||||||
|
public sealed class YandexError
|
||||||
|
{
|
||||||
|
[JsonPropertyName("name")]
|
||||||
|
public string? Name { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("message")]
|
||||||
|
public string? Message { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Search response.</summary>
|
||||||
|
public sealed class SearchResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("result")]
|
||||||
|
public SearchResult? Result { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Search result container.</summary>
|
||||||
|
public sealed class SearchResult
|
||||||
|
{
|
||||||
|
[JsonPropertyName("tracks")]
|
||||||
|
public SearchPage<TrackDto>? Tracks { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("albums")]
|
||||||
|
public SearchPage<AlbumDto>? Albums { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("artists")]
|
||||||
|
public SearchPage<ArtistDto>? Artists { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A page of search results.</summary>
|
||||||
|
public sealed class SearchPage<T>
|
||||||
|
{
|
||||||
|
[JsonPropertyName("results")]
|
||||||
|
public List<T> Results { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("total")]
|
||||||
|
public int Total { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cover object.</summary>
|
||||||
|
public sealed class CoverDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("uri")]
|
||||||
|
public string? Uri { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("color")]
|
||||||
|
public string? Color { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Track.</summary>
|
||||||
|
public sealed class TrackDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("id")]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("realId")]
|
||||||
|
public string? RealId { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("title")]
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("durationMs")]
|
||||||
|
public long? DurationMs { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("coverUri")]
|
||||||
|
public string? CoverUri { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("ogImage")]
|
||||||
|
public string? OgImage { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("explicit")]
|
||||||
|
public bool Explicit { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("lyricsAvailable")]
|
||||||
|
public bool LyricsAvailable { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("lyricsInfo")]
|
||||||
|
public LyricsInfoDto? LyricsInfo { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("artists")]
|
||||||
|
public List<ArtistDto> Artists { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("albums")]
|
||||||
|
public List<AlbumDto> Albums { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("major")]
|
||||||
|
public LabelDto? Major { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Lyrics availability info.</summary>
|
||||||
|
public sealed class LyricsInfoDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("hasLyrics")]
|
||||||
|
public bool HasLyrics { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("hasAvailableSyncLyrics")]
|
||||||
|
public bool HasAvailableSyncLyrics { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("hasAvailableTextLyrics")]
|
||||||
|
public bool HasAvailableTextLyrics { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Album or label reference.</summary>
|
||||||
|
public sealed class AlbumDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("id")]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("title")]
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("year")]
|
||||||
|
public int? Year { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("releaseDate")]
|
||||||
|
public string? ReleaseDate { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("genre")]
|
||||||
|
public string? Genre { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("metaType")]
|
||||||
|
public string? MetaType { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("type")]
|
||||||
|
public string? Type { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("coverUri")]
|
||||||
|
public string? CoverUri { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("ogImage")]
|
||||||
|
public string? OgImage { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("trackCount")]
|
||||||
|
public int? TrackCount { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("artists")]
|
||||||
|
public List<ArtistDto> Artists { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("labels")]
|
||||||
|
[JsonConverter(typeof(LabelListConverter))]
|
||||||
|
public List<LabelDto> Labels { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("volumes")]
|
||||||
|
public List<List<long>> Volumes { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("explicit")]
|
||||||
|
public bool? Explicit { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Label.</summary>
|
||||||
|
public sealed class LabelDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("id")]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("name")]
|
||||||
|
public string? Name { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Artist.</summary>
|
||||||
|
public sealed class ArtistDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("id")]
|
||||||
|
[JsonConverter(typeof(FlexibleLongConverter))]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("name")]
|
||||||
|
public string? Name { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("cover")]
|
||||||
|
public CoverDto? Cover { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("ogImage")]
|
||||||
|
public string? OgImage { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("genres")]
|
||||||
|
public List<string> Genres { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("description")]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("counts")]
|
||||||
|
public ArtistCountsDto? Counts { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("links")]
|
||||||
|
public List<ArtistLinkDto> Links { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Artist counters.</summary>
|
||||||
|
public sealed class ArtistCountsDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("tracks")]
|
||||||
|
public int Tracks { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("directAlbums")]
|
||||||
|
public int DirectAlbums { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Artist link.</summary>
|
||||||
|
public sealed class ArtistLinkDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("title")]
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("href")]
|
||||||
|
public string? Href { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("type")]
|
||||||
|
public string? Type { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("socialNetwork")]
|
||||||
|
public string? SocialNetwork { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Response of /artists/{id}/info.</summary>
|
||||||
|
public sealed class ArtistInfoResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("artist")]
|
||||||
|
public ArtistDto? Artist { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("description")]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("covers")]
|
||||||
|
public List<CoverDto> Covers { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("links")]
|
||||||
|
public List<ArtistLinkDto> Links { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("likesCount")]
|
||||||
|
public long? LikesCount { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Response of /artists/{id}/brief-info.</summary>
|
||||||
|
public sealed class ArtistBriefResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("result")]
|
||||||
|
public ArtistBriefDto? Result { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Brief artist info.</summary>
|
||||||
|
public sealed class ArtistBriefDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("artist")]
|
||||||
|
public ArtistDto? Artist { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("similarArtists")]
|
||||||
|
public List<ArtistDto> SimilarArtists { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("allCovers")]
|
||||||
|
public List<CoverDto> AllCovers { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("albums")]
|
||||||
|
public List<AlbumDto> Albums { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Genre tree node.</summary>
|
||||||
|
public sealed class GenreDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("id")]
|
||||||
|
public string? Id { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("title")]
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("titles")]
|
||||||
|
public Dictionary<string, GenreTitleDto> Titles { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("subGenres")]
|
||||||
|
public List<GenreDto> SubGenres { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Localized genre title.</summary>
|
||||||
|
public sealed class GenreTitleDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("title")]
|
||||||
|
public string? Title { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("fullTitle")]
|
||||||
|
public string? FullTitle { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Lyrics lookup response.</summary>
|
||||||
|
public sealed class LyricsResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("result")]
|
||||||
|
public LyricsResultDto? Result { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Lyrics download info.</summary>
|
||||||
|
public sealed class LyricsResultDto
|
||||||
|
{
|
||||||
|
[JsonPropertyName("downloadUrl")]
|
||||||
|
public string? DownloadUrl { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("writers")]
|
||||||
|
public List<string> Writers { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("lyricId")]
|
||||||
|
public long? LyricId { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>OAuth device code response.</summary>
|
||||||
|
public sealed class DeviceCodeResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("device_code")]
|
||||||
|
public string DeviceCode { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("user_code")]
|
||||||
|
public string UserCode { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("verification_url")]
|
||||||
|
public string VerificationUrl { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("expires_in")]
|
||||||
|
public int ExpiresIn { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("interval")]
|
||||||
|
public int Interval { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>OAuth token response.</summary>
|
||||||
|
public sealed class OAuthTokenResponse
|
||||||
|
{
|
||||||
|
[JsonPropertyName("access_token")]
|
||||||
|
public string? AccessToken { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("refresh_token")]
|
||||||
|
public string? RefreshToken { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("expires_in")]
|
||||||
|
public int? ExpiresIn { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("token_type")]
|
||||||
|
public string? TokenType { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("error")]
|
||||||
|
public string? Error { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("error_description")]
|
||||||
|
public string? ErrorDescription { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Configuration;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Minimal client for the (unofficial) Yandex Music API.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class YandexMusicClient
|
||||||
|
{
|
||||||
|
private const string ApiBase = "https://api.music.yandex.net";
|
||||||
|
private const string OAuthBase = "https://oauth.yandex.ru";
|
||||||
|
|
||||||
|
// Public OAuth credentials of the official Yandex Music Android app (same values
|
||||||
|
// the yandex-music-api project uses for its device flow).
|
||||||
|
private const string OAuthClientId = "23cabbbdc6cd418abb4b39c32c41195d";
|
||||||
|
private const string OAuthClientSecret = "53bc75238f0c4d08a118e51fe9203300";
|
||||||
|
|
||||||
|
// Key used by Yandex clients to sign lyrics requests.
|
||||||
|
private const string LyricsSignKey = "p93jhgh689SBReK6ghtw62";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||||
|
{
|
||||||
|
PropertyNameCaseInsensitive = true
|
||||||
|
};
|
||||||
|
|
||||||
|
private static readonly HashSet<string> AllowedImageHosts = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
"avatars.yandex.net",
|
||||||
|
"avatars.mds.yandex.net",
|
||||||
|
"img-fotki.yandex.ru",
|
||||||
|
"music.yandex.ru"
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly ILogger<YandexMusicClient> _logger;
|
||||||
|
private readonly SemaphoreSlim _throttle = new(4, 4);
|
||||||
|
private readonly SemaphoreSlim _genreLock = new(1, 1);
|
||||||
|
private Dictionary<string, string>? _genreCache;
|
||||||
|
private string _genreCacheLanguage = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="YandexMusicClient"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="logger">Logger.</param>
|
||||||
|
public YandexMusicClient(ILogger<YandexMusicClient> logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_http = new HttpClient
|
||||||
|
{
|
||||||
|
Timeout = TimeSpan.FromSeconds(20)
|
||||||
|
};
|
||||||
|
_http.DefaultRequestHeaders.UserAgent.ParseAdd("JellyfinYandexMusic/1.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
|
|
||||||
|
private static string? Token
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var token = Config.Token;
|
||||||
|
return string.IsNullOrWhiteSpace(token) ? null : token.Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets a value indicating whether a token is configured.
|
||||||
|
/// </summary>
|
||||||
|
public static bool HasToken => Token is not null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds a full image URL from a Yandex cover uri template.
|
||||||
|
/// </summary>
|
||||||
|
public static string? BuildCoverUrl(string? coverUri, int size = 1000)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(coverUri))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var uri = coverUri.Contains("%%", StringComparison.Ordinal)
|
||||||
|
? coverUri.Replace("%%", string.Format(CultureInfo.InvariantCulture, "{0}x{0}", size), StringComparison.Ordinal)
|
||||||
|
: coverUri;
|
||||||
|
|
||||||
|
if (uri.StartsWith("//", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return "https:" + uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
return uri.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? uri : "https://" + uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Searches tracks.</summary>
|
||||||
|
public Task<List<TrackDto>> SearchTracksAsync(string query, CancellationToken cancellationToken)
|
||||||
|
=> SearchAsync(query, "track", p => p.Tracks, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Searches albums.</summary>
|
||||||
|
public Task<List<AlbumDto>> SearchAlbumsAsync(string query, CancellationToken cancellationToken)
|
||||||
|
=> SearchAsync(query, "album", p => p.Albums, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Searches artists.</summary>
|
||||||
|
public Task<List<ArtistDto>> SearchArtistsAsync(string query, CancellationToken cancellationToken)
|
||||||
|
=> SearchAsync(query, "artist", p => p.Artists, cancellationToken);
|
||||||
|
|
||||||
|
private async Task<List<T>> SearchAsync<T>(
|
||||||
|
string query,
|
||||||
|
string type,
|
||||||
|
Func<SearchResult, SearchPage<T>?> selector,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(query))
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var path = string.Format(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
"/search?text={0}&type={1}&page=0&nocorrect=false",
|
||||||
|
Uri.EscapeDataString(query),
|
||||||
|
type);
|
||||||
|
|
||||||
|
var response = await GetJsonAsync<SearchResponse>(path, false, cancellationToken).ConfigureAwait(false);
|
||||||
|
var page = response?.Result is null ? null : selector(response.Result);
|
||||||
|
return page?.Results ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets a track by id.</summary>
|
||||||
|
public async Task<TrackDto?> GetTrackAsync(long id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await GetJsonAsync<YandexResponse<List<TrackDto>>>(
|
||||||
|
string.Format(CultureInfo.InvariantCulture, "/tracks/{0}?with-albums=true", id),
|
||||||
|
false,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
return response?.Result?.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets an album by id.</summary>
|
||||||
|
public async Task<AlbumDto?> GetAlbumAsync(long id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await GetJsonAsync<YandexResponse<AlbumDto>>(
|
||||||
|
string.Format(CultureInfo.InvariantCulture, "/albums/{0}", id),
|
||||||
|
false,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
return response?.Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets an artist by id.</summary>
|
||||||
|
public async Task<ArtistDto?> GetArtistAsync(long id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await GetJsonAsync<YandexResponse<ArtistDto>>(
|
||||||
|
string.Format(CultureInfo.InvariantCulture, "/artists/{0}", id),
|
||||||
|
false,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
return response?.Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gets the extended artist card (bio, covers, links).</summary>
|
||||||
|
public async Task<ArtistInfoResponse?> GetArtistInfoAsync(long id, CancellationToken cancellationToken)
|
||||||
|
=> await GetJsonAsync<ArtistInfoResponse>(
|
||||||
|
string.Format(CultureInfo.InvariantCulture, "/artists/{0}/info", id),
|
||||||
|
false,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
/// <summary>Gets similar artists and covers.</summary>
|
||||||
|
public async Task<ArtistBriefDto?> GetArtistBriefAsync(long id, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await GetJsonAsync<ArtistBriefResponse>(
|
||||||
|
string.Format(CultureInfo.InvariantCulture, "/artists/{0}/brief-info", id),
|
||||||
|
false,
|
||||||
|
cancellationToken).ConfigureAwait(false);
|
||||||
|
return response?.Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolves a Yandex genre id (e.g. "rusrap") to a human readable name.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<string?> GetGenreNameAsync(string? genreId, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(genreId))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Dictionary<string, string>> GetGenresAsync(string language, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (_genreCache is not null && string.Equals(_genreCacheLanguage, language, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return _genreCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _genreLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_genreCache is not null && string.Equals(_genreCacheLanguage, language, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return _genreCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
var response = await GetJsonAsync<YandexResponse<List<GenreDto>>>("/genres", false, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
foreach (var genre in response?.Result ?? [])
|
||||||
|
{
|
||||||
|
AddGenre(map, genre, language);
|
||||||
|
}
|
||||||
|
|
||||||
|
_genreCache = map;
|
||||||
|
_genreCacheLanguage = language;
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_genreLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddGenre(Dictionary<string, string> map, GenreDto genre, string language)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(genre.Id))
|
||||||
|
{
|
||||||
|
string? title = null;
|
||||||
|
if (genre.Titles.TryGetValue(language, out var localized))
|
||||||
|
{
|
||||||
|
title = localized.Title;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(title) && genre.Titles.TryGetValue("ru", out var russian))
|
||||||
|
{
|
||||||
|
title = russian.Title;
|
||||||
|
}
|
||||||
|
|
||||||
|
map[genre.Id] = string.IsNullOrWhiteSpace(title) ? genre.Title ?? genre.Id : title;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var child in genre.SubGenres)
|
||||||
|
{
|
||||||
|
AddGenre(map, child, language);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Downloads lyrics text. Returns null when there is no token or no lyrics.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<string?> GetLyricsTextAsync(long trackId, string format, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var token = Token;
|
||||||
|
if (token is null || !Config.EnableLyrics)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||||
|
var payload = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}{1}", trackId, timestamp));
|
||||||
|
var signature = Convert.ToBase64String(
|
||||||
|
HMACSHA256.HashData(Encoding.UTF8.GetBytes(LyricsSignKey), payload));
|
||||||
|
|
||||||
|
var path = string.Format(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
"/tracks/{0}/lyrics?format={1}&timeStamp={2}&sign={3}",
|
||||||
|
trackId,
|
||||||
|
Uri.EscapeDataString(format),
|
||||||
|
timestamp,
|
||||||
|
Uri.EscapeDataString(signature));
|
||||||
|
|
||||||
|
var response = await GetJsonAsync<LyricsResponse>(path, true, cancellationToken).ConfigureAwait(false);
|
||||||
|
var url = response?.Result?.DownloadUrl;
|
||||||
|
if (string.IsNullOrWhiteSpace(url))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||||
|
using var result = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!result.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Yandex Music lyrics download failed with {Status}", result.StatusCode);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Failed to download Yandex Music lyrics for track {TrackId}", trackId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Downloads an image from an allowed Yandex host.</summary>
|
||||||
|
public async Task<byte[]?> GetImageBytesAsync(string url, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || !AllowedImageHosts.Contains(uri.Host))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Refusing to download image from untrusted host {Url}", url);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var response = await _http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts Yandex OAuth device flow.</summary>
|
||||||
|
public async Task<DeviceCodeResponse?> RequestDeviceCodeAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var deviceId = Convert.ToHexString(RandomNumberGenerator.GetBytes(5));
|
||||||
|
var form = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["client_id"] = OAuthClientId,
|
||||||
|
["device_id"] = deviceId,
|
||||||
|
["device_name"] = "Jellyfin"
|
||||||
|
};
|
||||||
|
|
||||||
|
using var content = new FormUrlEncodedContent(form);
|
||||||
|
using var response = await _http.PostAsync($"{OAuthBase}/device/code", content, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_logger.LogError("Yandex device code request failed: {Status} {Body}", response.StatusCode, body);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return JsonSerializer.Deserialize<DeviceCodeResponse>(body, JsonOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Polls the device token once. Returns null while the user has not confirmed the code yet.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<OAuthTokenResponse?> PollDeviceTokenAsync(string deviceCode, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var form = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["grant_type"] = "device_code",
|
||||||
|
["code"] = deviceCode,
|
||||||
|
["client_id"] = OAuthClientId,
|
||||||
|
["client_secret"] = OAuthClientSecret
|
||||||
|
};
|
||||||
|
|
||||||
|
using var content = new FormUrlEncodedContent(form);
|
||||||
|
using var response = await _http.PostAsync($"{OAuthBase}/token", content, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var token = JsonSerializer.Deserialize<OAuthTokenResponse>(body, JsonOptions);
|
||||||
|
|
||||||
|
if (response.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(token?.AccessToken))
|
||||||
|
{
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token?.Error == "authorization_pending" || body.Contains("authorization_pending", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogWarning("Yandex token poll failed: {Status} {Body}", response.StatusCode, body);
|
||||||
|
return new OAuthTokenResponse { Error = token?.Error ?? "unknown_error", ErrorDescription = token?.ErrorDescription };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Checks that the API is reachable and the token (if any) works.</summary>
|
||||||
|
public async Task<bool> TestConnectionAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var response = await GetJsonAsync<SearchResponse>("/search?text=test&type=track&page=0", false, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return response?.Result is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<T?> GetJsonAsync<T>(string path, bool auth, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await _throttle.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (var attempt = 0; attempt < 3; attempt++)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, ApiBase + path);
|
||||||
|
request.Headers.TryAddWithoutValidation("User-Agent", "YandexMusicAPI/1.0");
|
||||||
|
if (auth && Token is { } token)
|
||||||
|
{
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", token);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (response.StatusCode is HttpStatusCode.TooManyRequests or HttpStatusCode.ServiceUnavailable
|
||||||
|
or HttpStatusCode.BadGateway)
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromMilliseconds(400 * (attempt + 1)), cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Yandex Music returned {Status} for {Path}", response.StatusCode, path);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Yandex Music returned {Status} for {Path}", response.StatusCode, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
|
||||||
|
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return await JsonSerializer.DeserializeAsync<T>(stream, JsonOptions, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (JsonException ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Failed to parse Yandex Music response for {Path}", path);
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
catch (HttpRequestException ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Yandex Music request failed for {Path}", path);
|
||||||
|
if (attempt == 2)
|
||||||
|
{
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_throttle.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Yandex Music для Jellyfin
|
||||||
|
|
||||||
|
Плагин метаданных, который берёт информацию из Яндекс.Музыки (`music.yandex.ru`) через её неофициальное API.
|
||||||
|
|
||||||
|
## Что даёт
|
||||||
|
|
||||||
|
- **Треки**: официальное название, исполнители, альбом, год и дата релиза, жанр, лейбл, номер трека и диска, обложка.
|
||||||
|
- **Альбомы**: название, исполнители, год/дата, жанр, лейбл, обложка.
|
||||||
|
- **Исполнители**: биография, жанры, фото и дополнительные изображения.
|
||||||
|
- **Тексты песен**: синхронизированные (LRC) или обычные, если указан OAuth-токен Яндекса.
|
||||||
|
- **Ссылки** на карточки артиста/альбома/трека на music.yandex.ru и внешние ID для повторного матчинга.
|
||||||
|
|
||||||
|
Метаданные без токена: поиск, треки, альбомы, исполнители, жанры и обложки работают анонимно.
|
||||||
|
Токен нужен только для текстов песен.
|
||||||
|
|
||||||
|
## Установка
|
||||||
|
|
||||||
|
Плагин ставится как обычный плагин Jellyfin из репозитория (Dashboard → Plugins → Manage Repositories).
|
||||||
|
|
||||||
|
## Настройка
|
||||||
|
|
||||||
|
Dashboard → Plugins → Yandex Music:
|
||||||
|
|
||||||
|
- **Войти в Яндекс** — OAuth Device Flow: плагин покажет код и ссылку, после подтверждения токен сохранится сам.
|
||||||
|
- Тумблеры для треков/альбомов/исполнителей/обложек/текстов/жанров/лейблов.
|
||||||
|
- **Порог совпадения** — насколько уверенно результат поиска должен совпасть с тегами файла.
|
||||||
|
- **Допуск по длительности** — используется при поиске обложек и текстов.
|
||||||
|
- **Подставлять настоящее название альбома** — по умолчанию выключено.
|
||||||
|
|
||||||
|
## Сборка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet publish Jellyfin.Plugin.YandexMusic/Jellyfin.Plugin.YandexMusic.csproj -c Release -o publish
|
||||||
|
./scripts/package.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Требуется .NET 10 SDK и Jellyfin 12.4+.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
- API Яндекс.Музыки неофициальное и может меняться.
|
||||||
|
- Тексты песен требуют подписку Яндекса и токен.
|
||||||
|
- Плагин меняет только базу Jellyfin, файлы на диске не перезаписываются.
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
name: "Yandex Music"
|
||||||
|
guid: "f3b9626b-da14-4cbf-8ad1-33b92cfa6656"
|
||||||
|
version: "1.0.0.0"
|
||||||
|
targetAbi: "12.4.0.0"
|
||||||
|
framework: "net10.0"
|
||||||
|
overview: "Metadata for music from Yandex Music."
|
||||||
|
description: >
|
||||||
|
Fetches track, album and artist metadata, cover art, genres, labels,
|
||||||
|
release dates and lyrics from Yandex Music (music.yandex.ru).
|
||||||
|
category: "Music"
|
||||||
|
owner: "kirill"
|
||||||
|
artifacts:
|
||||||
|
- "Jellyfin.Plugin.YandexMusic.dll"
|
||||||
|
changelog: >
|
||||||
|
First release.
|
||||||
Executable
+51
@@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
VERSION="1.0.0.0"
|
||||||
|
NAME="Jellyfin.Plugin.YandexMusic"
|
||||||
|
PUBLISH_DIR="publish"
|
||||||
|
ARTIFACTS_DIR="artifacts"
|
||||||
|
BASE_URL="${BASE_URL:-}"
|
||||||
|
DOTNET_BIN="${DOTNET_BIN:-$HOME/.dotnet/dotnet}"
|
||||||
|
|
||||||
|
"$DOTNET_BIN" publish "$NAME/$NAME.csproj" -c Release -o "$PUBLISH_DIR"
|
||||||
|
|
||||||
|
rm -rf "$ARTIFACTS_DIR"
|
||||||
|
mkdir -p "$ARTIFACTS_DIR"
|
||||||
|
|
||||||
|
ZIP_NAME="${NAME}_${VERSION}.zip"
|
||||||
|
(cd "$PUBLISH_DIR" && zip -qr "../$ARTIFACTS_DIR/$ZIP_NAME" .)
|
||||||
|
|
||||||
|
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'
|
||||||
|
import json, sys, os
|
||||||
|
artifacts, zip_name, checksum, timestamp, version, base_url = sys.argv[1:]
|
||||||
|
source = f"{base_url.rstrip('/')}/{zip_name}" if base_url else zip_name
|
||||||
|
manifest = [{
|
||||||
|
"guid": "f3b9626b-da14-4cbf-8ad1-33b92cfa6656",
|
||||||
|
"name": "Yandex Music",
|
||||||
|
"description": "Metadata, cover art and lyrics from Yandex Music.",
|
||||||
|
"overview": "Metadata for music from Yandex Music.",
|
||||||
|
"owner": "kirill",
|
||||||
|
"category": "Music",
|
||||||
|
"imageUrl": "",
|
||||||
|
"versions": [{
|
||||||
|
"version": version,
|
||||||
|
"changelog": "First release.",
|
||||||
|
"targetAbi": "12.4.0.0",
|
||||||
|
"sourceUrl": source,
|
||||||
|
"checksum": checksum,
|
||||||
|
"timestamp": timestamp
|
||||||
|
}]
|
||||||
|
}]
|
||||||
|
with open(os.path.join(artifacts, "manifest.json"), "w", encoding="utf-8") as f:
|
||||||
|
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "Package: $ARTIFACTS_DIR/$ZIP_NAME"
|
||||||
|
echo "Checksum: $CHECKSUM"
|
||||||
|
echo "Manifest: $ARTIFACTS_DIR/manifest.json"
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
using Jellyfin.Plugin.YandexMusic.Matching;
|
||||||
|
using Jellyfin.Plugin.YandexMusic.Yandex;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
|
||||||
|
var client = new YandexMusicClient(NullLogger<YandexMusicClient>.Instance);
|
||||||
|
|
||||||
|
Console.WriteLine("== search ==");
|
||||||
|
var rawUrl = "https://api.music.yandex.net/search?text=" + Uri.EscapeDataString("Чёрная Тайга STAREDOWN") + "&type=track&page=0&nocorrect=false";
|
||||||
|
using (var rawHttp = new HttpClient())
|
||||||
|
{
|
||||||
|
var raw = await rawHttp.GetAsync(rawUrl);
|
||||||
|
Console.WriteLine($"raw status: {(int)raw.StatusCode}");
|
||||||
|
var body = await raw.Content.ReadAsStringAsync();
|
||||||
|
Console.WriteLine($"raw body: {body[..Math.Min(400, body.Length)]}");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var parsed = System.Text.Json.JsonSerializer.Deserialize<SearchResponse>(
|
||||||
|
body,
|
||||||
|
new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
Console.WriteLine($"parsed directly: tracks={parsed?.Result?.Tracks?.Results.Count}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"parse error: {ex}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var tracks = await client.SearchTracksAsync("Чёрная Тайга STAREDOWN", CancellationToken.None);
|
||||||
|
Console.WriteLine($"tracks: {tracks.Count}");
|
||||||
|
foreach (var t in tracks.Take(5))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"{t.Id} | {string.Join(", ", t.Artists.Select(a => a.Name))} - {t.Title} | {t.DurationMs} ms | album={t.Albums.FirstOrDefault()?.Title}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var match = MatchScoring.FindBestTrack(tracks, "STAREDOWN", ["Чёрная Тайга"], 220290, 0.72, 12);
|
||||||
|
Console.WriteLine($"match: {match?.Score:F3} {match?.Track.Title}");
|
||||||
|
|
||||||
|
if (match is { } m)
|
||||||
|
{
|
||||||
|
var album = await client.GetAlbumAsync(m.Track.Albums[0].Id, CancellationToken.None);
|
||||||
|
var labelNames = album?.Labels.Select(l => l.Name ?? string.Empty).ToArray() ?? [];
|
||||||
|
Console.WriteLine($"album: {album?.Title} {album?.Year} genre={album?.Genre} labels={string.Join(",", labelNames)}");
|
||||||
|
var genre = await client.GetGenreNameAsync(album?.Genre, CancellationToken.None);
|
||||||
|
Console.WriteLine($"genre name: {genre}");
|
||||||
|
var cover = YandexMusicClient.BuildCoverUrl(album?.CoverUri ?? m.Track.CoverUri, 600);
|
||||||
|
Console.WriteLine($"cover: {cover}");
|
||||||
|
var bytes = cover is null ? null : await client.GetImageBytesAsync(cover, CancellationToken.None);
|
||||||
|
Console.WriteLine($"cover bytes: {bytes?.Length}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine("== artist ==");
|
||||||
|
var artists = await client.SearchArtistsAsync("10AGE", CancellationToken.None);
|
||||||
|
var artist = MatchScoring.FindBestArtist(artists, "10AGE");
|
||||||
|
Console.WriteLine($"artist: {artist?.Id} {artist?.Name} genres={string.Join(",", artist?.Genres ?? new List<string>())}");
|
||||||
|
if (artist is not null)
|
||||||
|
{
|
||||||
|
var info = await client.GetArtistInfoAsync(artist.Id, CancellationToken.None);
|
||||||
|
Console.WriteLine($"bio: {info?.Description?.Length} chars, covers={info?.Covers.Count}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine("== genres endpoint ==");
|
||||||
|
Console.WriteLine($"genre 6504263 first: {await client.GetGenreNameAsync("rusrap", CancellationToken.None)}");
|
||||||
|
|
||||||
|
Console.WriteLine("== library batch ==");
|
||||||
|
if (File.Exists("/tmp/lib_simple.json"))
|
||||||
|
{
|
||||||
|
using var doc = System.Text.Json.JsonDocument.Parse(File.ReadAllText("/tmp/lib_simple.json"));
|
||||||
|
foreach (var el in doc.RootElement.EnumerateArray())
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
Console.WriteLine(hit is null
|
||||||
|
? $"MISS {name} / {string.Join(", ", libArtists)} (candidates {found.Count})"
|
||||||
|
: $"ok {hit.Value.Score:F2} {name} -> {string.Join(", ", hit.Value.Track.Artists.Select(a => a.Name))} - {hit.Value.Track.Title}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="../../Jellyfin.Plugin.YandexMusic/Jellyfin.Plugin.YandexMusic.csproj" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" />
|
||||||
|
<PackageReference Include="Jellyfin.Model" Version="12.4.0" />
|
||||||
|
<PackageReference Include="Jellyfin.Controller" Version="12.4.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
Reference in new issue
Block a user