using System.Collections.Concurrent; using Jellyfin.Plugin.YandexMusic.Yandex; using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Plugin.YandexMusic.Api; /// /// Plugin API used by the configuration page for Yandex OAuth device flow. /// [ApiController] [Route("YandexMusic")] [Authorize(Policy = "RequiresElevation")] public class YandexMusicController : ControllerBase { private static readonly ConcurrentDictionary Sessions = new(); private readonly YandexMusicClient _client; private readonly IServerApplicationPaths _paths; private readonly ILibraryManager _libraryManager; /// /// Initializes a new instance of the class. /// public YandexMusicController( YandexMusicClient client, IServerApplicationPaths paths, ILibraryManager libraryManager) { _client = client; _paths = paths; _libraryManager = libraryManager; } /// Starts the device flow. [HttpPost("DeviceCode")] public async Task> 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)); } /// Polls the device flow once. [HttpPost("DeviceCode/Poll")] public async Task> 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); } /// Returns connection status. [HttpGet("Status")] public async Task> 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 недоступен"); } /// /// Removes broken virtual-folder entries (e.g. a library left without an item id or paths), /// which Jellyfin cannot delete through its own API. /// [HttpPost("RepairLibraries")] public ActionResult RepairLibraries() { var live = _libraryManager.GetVirtualFolders(); var deleted = new List(); if (Directory.Exists(_paths.DefaultUserViewsPath)) { foreach (var directory in Directory.EnumerateDirectories(_paths.DefaultUserViewsPath)) { var name = Path.GetFileName(directory); var info = live.FirstOrDefault(v => string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase)); var broken = info is null || string.IsNullOrEmpty(info.ItemId) || info.Locations.Length == 0; if (broken) { try { Directory.Delete(directory, true); deleted.Add(name); } catch (Exception ex) { return StatusCode(500, new { error = ex.Message, name }); } } } } return new RepairLibrariesResult( deleted, live.Where(v => !deleted.Contains(v.Name, StringComparer.OrdinalIgnoreCase)) .Select(v => v.Name) .ToList()); } /// Clears the saved token. [HttpPost("Logout")] public ActionResult Logout() { var config = Plugin.Instance!.Configuration; config.Token = string.Empty; Plugin.Instance.UpdateConfiguration(config); return NoContent(); } } /// Device code returned to the config page. public record DeviceCodeResult( string DeviceCode, string UserCode, string VerificationUrl, int ExpiresIn, int Interval); /// Device poll request. public record DevicePollRequest(string DeviceCode); /// Device poll result. public record DevicePollResult(string Status, string? Token, string? Error); /// Plugin status. public record StatusResult(bool Connected, bool HasToken, string? Error); /// Result of the broken-library cleanup. public record RepairLibrariesResult(List Deleted, List Remaining);