Yandex Music metadata plugin for Jellyfin 12.4

This commit is contained in:
opencode committed 2026-11-27 18:56:15 +03:00
commit c3dc901337
25 files changed
+3233

No files matched your search

@@ -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();
}
}
}