454 lines
17 KiB
C#
454 lines
17 KiB
C#
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();
|
|
}
|
|
}
|
|
}
|