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; /// /// Minimal client for the (unofficial) Yandex Music API. /// 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 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 _logger; private readonly SemaphoreSlim _throttle = new(4, 4); private readonly SemaphoreSlim _genreLock = new(1, 1); private Dictionary? _genreCache; private string _genreCacheLanguage = string.Empty; private readonly System.Collections.Concurrent.ConcurrentDictionary _artistGenres = new(); private readonly System.Collections.Concurrent.ConcurrentDictionary> _credits = new(); /// /// Initializes a new instance of the class. /// /// Logger. public YandexMusicClient(ILogger 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(); } } /// /// Gets a value indicating whether a token is configured. /// public static bool HasToken => Token is not null; /// /// Builds a full image URL from a Yandex cover uri template. /// 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; } /// Searches tracks. public Task> SearchTracksAsync(string query, CancellationToken cancellationToken) => SearchAsync(query, "track", p => p.Tracks, cancellationToken); /// Searches albums. public Task> SearchAlbumsAsync(string query, CancellationToken cancellationToken) => SearchAsync(query, "album", p => p.Albums, cancellationToken); /// Searches artists. public Task> SearchArtistsAsync(string query, CancellationToken cancellationToken) => SearchAsync(query, "artist", p => p.Artists, cancellationToken); private async Task> SearchAsync( string query, string type, Func?> 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(path, false, cancellationToken).ConfigureAwait(false); var page = response?.Result is null ? null : selector(response.Result); return page?.Results ?? []; } /// Gets a track by id. public async Task GetTrackAsync(long id, CancellationToken cancellationToken) { var response = await GetJsonAsync>>( string.Format(CultureInfo.InvariantCulture, "/tracks/{0}?with-albums=true", id), false, cancellationToken).ConfigureAwait(false); return response?.Result?.FirstOrDefault(); } /// Gets an album by id. public async Task GetAlbumAsync(long id, CancellationToken cancellationToken) { var response = await GetJsonAsync>( string.Format(CultureInfo.InvariantCulture, "/albums/{0}", id), false, cancellationToken).ConfigureAwait(false); return response?.Result; } /// Gets an artist by id. public async Task GetArtistAsync(long id, CancellationToken cancellationToken) { var response = await GetJsonAsync>( string.Format(CultureInfo.InvariantCulture, "/artists/{0}", id), false, cancellationToken).ConfigureAwait(false); return response?.Result?.Artist; } /// Gets the extended artist card (bio, covers, links). public async Task GetArtistInfoAsync(long id, CancellationToken cancellationToken) => await GetJsonAsync( string.Format(CultureInfo.InvariantCulture, "/artists/{0}/info", id), false, cancellationToken).ConfigureAwait(false); /// Gets an artist's genre ids, cached per artist. public async Task GetArtistGenresAsync(long artistId, CancellationToken cancellationToken) { if (_artistGenres.TryGetValue(artistId, out var cached)) { return cached; } var artist = await GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false); var genres = artist?.Genres.ToArray() ?? []; _artistGenres[artistId] = genres; return genres; } /// Gets track credits (composers, lyricists, label), cached per track. public async Task> GetTrackCreditsAsync(long trackId, CancellationToken cancellationToken) { if (_credits.TryGetValue(trackId, out var cached)) { return cached; } var response = await GetJsonAsync( string.Format(CultureInfo.InvariantCulture, "/tracks/{0}/credits", trackId), false, cancellationToken).ConfigureAwait(false); var credits = response?.Result?.Credits ?? []; _credits[trackId] = credits; return credits; } /// Gets similar artists and covers. public async Task GetArtistBriefAsync(long id, CancellationToken cancellationToken) { var response = await GetJsonAsync( string.Format(CultureInfo.InvariantCulture, "/artists/{0}/brief-info", id), false, cancellationToken).ConfigureAwait(false); return response?.Result; } /// /// Resolves a Yandex genre id (e.g. "rusrap") to a human readable name. /// public async Task 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 : Jellyfin.Plugin.YandexMusic.Providers.GenreNameMap.Normalize(genreId); } private async Task> 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>>("/genres", false, cancellationToken) .ConfigureAwait(false); var map = new Dictionary(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 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); } } /// /// Downloads lyrics text. Returns null when there is no token or no lyrics. /// public async Task 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(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; } } /// /// Gets plain lyrics from the track supplement endpoint. Works even though the signed /// /lyrics endpoint currently rejects signatures with "Invalid Sign". /// public async Task GetSupplementLyricsAsync(long trackId, CancellationToken cancellationToken) { if (Token is null || !Config.EnableLyrics) { return null; } var response = await GetJsonAsync( string.Format(CultureInfo.InvariantCulture, "/tracks/{0}/supplement", trackId), true, cancellationToken).ConfigureAwait(false); var text = response?.Result?.Lyrics?.FullLyrics; if (string.IsNullOrWhiteSpace(text)) { text = response?.Result?.Lyrics?.Lyrics; } return string.IsNullOrWhiteSpace(text) ? null : text.TrimStart('\uFEFF', '\u200B', ' ', '\r', '\n'); } /// Downloads an image from an allowed Yandex host. public async Task 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); } /// Starts Yandex OAuth device flow. public async Task RequestDeviceCodeAsync(CancellationToken cancellationToken) { var deviceId = Convert.ToHexString(RandomNumberGenerator.GetBytes(5)); var form = new Dictionary { ["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(body, JsonOptions); } /// /// Polls the device token once. Returns null while the user has not confirmed the code yet. /// public async Task PollDeviceTokenAsync(string deviceCode, CancellationToken cancellationToken) { var form = new Dictionary { ["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(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 }; } /// Checks that the API is reachable and the token (if any) works. public async Task TestConnectionAsync(CancellationToken cancellationToken) { var response = await GetJsonAsync("/search?text=test&type=track&page=0", false, cancellationToken) .ConfigureAwait(false); return response?.Result is not null; } private async Task GetJsonAsync(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(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(); } } }