using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data; using Jellyfin.Database.Implementations.Enums; using Jellyfin.Plugin.Request.Configuration; using Jellyfin.Plugin.Request.Hosting; using Jellyfin.Plugin.Request.Storage; using Jellyfin.Plugin.Request.Tmdb; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Jellyfin.Plugin.Request.Api; /// /// REST API for searching media and managing the local request queue. /// [ApiController] [Authorize] [Route("Requests")] public sealed class RequestController : ControllerBase { private readonly RequestStore _store; private readonly TmdbClient _tmdbClient; private readonly IUserManager _userManager; private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// Request store. /// TMDB client. /// User manager. /// Logger. public RequestController( RequestStore store, TmdbClient tmdbClient, IUserManager userManager, ILogger logger) { _store = store; _tmdbClient = tmdbClient; _userManager = userManager; _logger = logger; } /// /// Returns non-secret plugin status for the request UI. /// /// Status payload. [HttpGet("Status")] [AllowAnonymous] public ActionResult Status() { var config = GetConfig(); var userId = GetUserId(); return Ok(new { isConfigured = !string.IsNullOrWhiteSpace(config.TmdbApiKey), requestSubmissionEnabled = config.EnableRequestSubmission, allowSeasonSelection = config.AllowSeasonSelection, isAuthenticated = userId != Guid.Empty, isAdmin = userId != Guid.Empty && IsAdministrator(userId) }); } /// /// Serves the standalone request page. /// /// HTML page. [HttpGet("Page")] [AllowAnonymous] public IActionResult Page() { return EmbeddedFile("Web.requestPage.html", "text/html; charset=utf-8"); } /// /// File Transformation endpoint: injects nav-loader.js into jellyfin-web index.html. /// Must stay anonymous because File Transformation calls it without auth. /// /// Current file contents. /// Transformed HTML body. [HttpPost("TransformIndexHtml")] [AllowAnonymous] public ContentResult TransformIndexHtml([FromBody] IndexHtmlPatchPayload payload) { var html = WebNavInjector.InjectHtml(payload?.Contents ?? string.Empty); return Content(html, "text/html; charset=utf-8"); } /// /// Serves plugin web assets. /// /// Asset file name. /// Asset response. [HttpGet("Assets/{assetName}")] [AllowAnonymous] public IActionResult Asset(string assetName) { var resource = assetName switch { "request.js" => ("Web.request.js", "application/javascript; charset=utf-8"), "request.css" => ("Web.request.css", "text/css; charset=utf-8"), "nav-loader.js" => ("Web.nav-loader.js", "application/javascript; charset=utf-8"), _ => ((string?)null, (string?)null) }; return resource.Item1 is null ? NotFound() : EmbeddedFile(resource.Item1, resource.Item2!); } /// /// Searches TMDB for movies or TV shows. /// /// Search query. /// movie, tv, or multi. /// Cancellation token. /// Search results. [HttpGet("Search")] public async Task>> Search( [FromQuery] string query, [FromQuery] string type = "multi", CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(query)) { return BadRequest(new { message = "Query is required." }); } var normalizedType = NormalizeMediaTypeFilter(type); if (normalizedType is null) { return BadRequest(new { message = "type must be movie, tv, or multi." }); } try { var results = await _tmdbClient.SearchAsync(query.Trim(), normalizedType, cancellationToken) .ConfigureAwait(false); return Ok(results); } catch (Exception ex) when (ex is InvalidOperationException or HttpRequestException or TaskCanceledException) { _logger.LogWarning(ex, "TMDB search failed"); return StatusCode(StatusCodes.Status502BadGateway, new { message = ex.Message }); } } /// /// Returns TMDB details for a movie or TV show. /// /// movie or tv. /// TMDB identifier. /// Cancellation token. /// Media detail. [HttpGet("Media/{type}/{tmdbId:int}")] public async Task> Media( string type, int tmdbId, CancellationToken cancellationToken = default) { var mediaType = NormalizeMediaType(type); if (mediaType is null || tmdbId <= 0) { return BadRequest(new { message = "type must be movie or tv and tmdbId must be positive." }); } try { var detail = await _tmdbClient.GetDetailsAsync(mediaType, tmdbId, cancellationToken).ConfigureAwait(false); return detail is null ? NotFound() : Ok(detail); } catch (Exception ex) when (ex is InvalidOperationException or HttpRequestException or TaskCanceledException) { _logger.LogWarning(ex, "TMDB detail failed for {Type}/{TmdbId}", mediaType, tmdbId); return StatusCode(StatusCodes.Status502BadGateway, new { message = ex.Message }); } } /// /// Lists requests visible to the current user. /// /// Cancellation token. /// Request list. [HttpGet] public async Task>> List(CancellationToken cancellationToken) { var userId = GetUserId(); if (userId == Guid.Empty) { return Unauthorized(); } var items = await _store.GetAllAsync(cancellationToken).ConfigureAwait(false); if (IsAdministrator(userId)) { return Ok(items.OrderByDescending(item => item.CreatedAtUtc).ToList()); } return Ok(items .Where(item => item.RequestedByUserId == userId) .OrderByDescending(item => item.CreatedAtUtc) .ToList()); } /// /// Creates a new media request. /// /// Request body. /// Cancellation token. /// Created request. [HttpPost] public async Task> Create( [FromBody] CreateRequestDto? body, CancellationToken cancellationToken) { var config = GetConfig(); if (!config.EnableRequestSubmission) { return StatusCode(StatusCodes.Status403Forbidden, new { message = "Request submission is disabled. Enable it in Dashboard → Plugins → Request." }); } var userId = GetUserId(); if (userId == Guid.Empty) { return Unauthorized(new { message = "You must be signed in to submit a request." }); } if (body is null) { return BadRequest(new { message = "Request body is required." }); } var mediaType = NormalizeMediaType(body.MediaType); if (mediaType is null) { return BadRequest(new { message = "mediaType must be movie or tv." }); } if (body.IsCustom) { var customTitle = (body.Title ?? string.Empty).Trim(); if (customTitle.Length is < 1 or > 200) { return BadRequest(new { message = "Custom requests need a title (1–200 characters)." }); } if (body.Year.HasValue && (body.Year.Value < 1870 || body.Year.Value > 2100)) { return BadRequest(new { message = "Year must be between 1870 and 2100 when provided." }); } var notes = string.IsNullOrWhiteSpace(body.Notes) ? null : body.Notes.Trim(); if (notes is { Length: > 1000 }) { return BadRequest(new { message = "Notes must be 1000 characters or fewer." }); } var existingCustom = await _store.GetAllAsync(cancellationToken).ConfigureAwait(false); if (HasCustomDuplicate(existingCustom, userId, mediaType, customTitle, body.Year)) { return Conflict(new { message = "You already have an open request for this custom title." }); } var customUser = _userManager.GetUserById(userId); var customRequest = new MediaRequest { Id = Guid.NewGuid(), MediaType = mediaType, TmdbId = 0, IsCustom = true, Title = customTitle, Year = body.Year, Notes = notes, PosterPath = null, Seasons = null, AllSeasons = mediaType == "tv", RequestedByUserId = userId, RequestedByName = customUser?.Username ?? "Unknown", CreatedAtUtc = DateTime.UtcNow, Status = RequestStatus.Pending }; await _store.AddAsync(customRequest, cancellationToken).ConfigureAwait(false); return StatusCode(StatusCodes.Status201Created, customRequest); } if (body.TmdbId <= 0) { return BadRequest(new { message = "tmdbId must be positive for TMDB requests." }); } var allSeasons = body.AllSeasons; List? seasons = null; if (mediaType == "tv") { if (!config.AllowSeasonSelection || body.AllSeasons || body.Seasons is null || body.Seasons.Count == 0) { allSeasons = true; seasons = null; } else if (body.Seasons.Any(season => season < 1)) { return BadRequest(new { message = "Season numbers must be positive integers." }); } else { allSeasons = false; seasons = body.Seasons.Distinct().OrderBy(season => season).ToList(); } } TmdbMediaDetail detail; try { detail = await _tmdbClient.GetDetailsAsync(mediaType, body.TmdbId, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Title was not found on TMDB."); } catch (Exception ex) when (ex is InvalidOperationException or HttpRequestException or TaskCanceledException) { return StatusCode(StatusCodes.Status502BadGateway, new { message = ex.Message }); } var existing = await _store.GetAllAsync(cancellationToken).ConfigureAwait(false); if (HasDuplicate(existing, userId, mediaType, body.TmdbId, allSeasons, seasons)) { return Conflict(new { message = "You already have an open request for this title." }); } var user = _userManager.GetUserById(userId); var request = new MediaRequest { Id = Guid.NewGuid(), MediaType = mediaType, TmdbId = detail.TmdbId, IsCustom = false, Title = detail.Title, Year = detail.Year, Notes = string.IsNullOrWhiteSpace(body.Notes) ? null : body.Notes.Trim(), PosterPath = detail.PosterPath, Seasons = seasons, AllSeasons = mediaType == "tv" && allSeasons, RequestedByUserId = userId, RequestedByName = user?.Username ?? "Unknown", CreatedAtUtc = DateTime.UtcNow, Status = RequestStatus.Pending }; await _store.AddAsync(request, cancellationToken).ConfigureAwait(false); return StatusCode(StatusCodes.Status201Created, request); } /// /// Approves a request. /// /// Request identifier. /// Optional note. /// Cancellation token. /// Updated request. [HttpPost("{id:guid}/approve")] public Task> Approve( Guid id, [FromBody] AdminNoteDto? body, CancellationToken cancellationToken) { return SetStatusAsync(id, RequestStatus.Approved, body?.AdminNote, cancellationToken); } /// /// Rejects a request. /// /// Request identifier. /// Optional note. /// Cancellation token. /// Updated request. [HttpPost("{id:guid}/reject")] public Task> Reject( Guid id, [FromBody] AdminNoteDto? body, CancellationToken cancellationToken) { return SetStatusAsync(id, RequestStatus.Rejected, body?.AdminNote, cancellationToken); } /// /// Marks a request as fulfilled. /// /// Request identifier. /// Optional note. /// Cancellation token. /// Updated request. [HttpPost("{id:guid}/fulfill")] public Task> Fulfill( Guid id, [FromBody] AdminNoteDto? body, CancellationToken cancellationToken) { return SetStatusAsync(id, RequestStatus.Fulfilled, body?.AdminNote, cancellationToken); } /// /// Deletes a request. /// /// Request identifier. /// Cancellation token. /// No content when deleted. [HttpDelete("{id:guid}")] public async Task Delete(Guid id, CancellationToken cancellationToken) { var userId = GetUserId(); if (userId == Guid.Empty) { return Unauthorized(new { message = "You must be signed in." }); } var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false); if (existing is null) { return NotFound(new { message = "Request not found." }); } var isAdmin = IsAdministrator(userId); if (!isAdmin && (existing.RequestedByUserId != userId || existing.Status != RequestStatus.Pending)) { return StatusCode(StatusCodes.Status403Forbidden, new { message = "You can only cancel your own pending requests." }); } await _store.DeleteAsync(id, cancellationToken).ConfigureAwait(false); return NoContent(); } private async Task> SetStatusAsync( Guid id, RequestStatus status, string? adminNote, CancellationToken cancellationToken) { var userId = GetUserId(); if (userId == Guid.Empty) { return Unauthorized(new { message = "You must be signed in." }); } if (!IsAdministrator(userId)) { return StatusCode(StatusCodes.Status403Forbidden, new { message = "Administrator access is required." }); } var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false); if (existing is null) { return NotFound(new { message = "Request not found." }); } existing.Status = status; if (!string.IsNullOrWhiteSpace(adminNote)) { existing.AdminNote = adminNote.Trim(); } await _store.UpdateAsync(existing, cancellationToken).ConfigureAwait(false); return Ok(existing); } private static bool HasDuplicate( IReadOnlyList existing, Guid userId, string mediaType, int tmdbId, bool allSeasons, List? seasons) { foreach (var item in existing) { if (item.RequestedByUserId != userId || item.IsCustom || !item.MediaType.Equals(mediaType, StringComparison.OrdinalIgnoreCase) || item.TmdbId != tmdbId || item.Status is not (RequestStatus.Pending or RequestStatus.Approved)) { continue; } if (mediaType == "movie") { return true; } if (item.AllSeasons || allSeasons) { return true; } if (item.Seasons is null || seasons is null) { return true; } if (item.Seasons.Intersect(seasons).Any()) { return true; } } return false; } private static bool HasCustomDuplicate( IReadOnlyList existing, Guid userId, string mediaType, string title, int? year) { foreach (var item in existing) { if (item.RequestedByUserId != userId || !item.IsCustom || !item.MediaType.Equals(mediaType, StringComparison.OrdinalIgnoreCase) || item.Status is not (RequestStatus.Pending or RequestStatus.Approved) || !item.Title.Equals(title, StringComparison.OrdinalIgnoreCase)) { continue; } if (year.HasValue && item.Year.HasValue && year.Value != item.Year.Value) { continue; } return true; } return false; } private static PluginConfiguration GetConfig() { return Plugin.Instance?.Configuration ?? new PluginConfiguration(); } private Guid GetUserId() { string?[] candidates = [ User.FindFirstValue(ClaimTypes.NameIdentifier), User.FindFirstValue("sub"), User.FindFirstValue("Jellyfin-UserId"), User.FindFirstValue("http://jellyfin.media/claims/user-id"), User.Claims.FirstOrDefault(claim => claim.Type.EndsWith("/nameidentifier", StringComparison.OrdinalIgnoreCase) || claim.Type.Equals("userid", StringComparison.OrdinalIgnoreCase))?.Value ]; foreach (var raw in candidates) { if (Guid.TryParse(raw, out var userId) && userId != Guid.Empty) { return userId; } } return Guid.Empty; } private bool IsAdministrator(Guid userId) { var user = _userManager.GetUserById(userId); return user?.HasPermission(PermissionKind.IsAdministrator) == true; } private static string? NormalizeMediaType(string? value) { return value?.Trim().ToLowerInvariant() switch { "movie" => "movie", "tv" or "series" or "show" => "tv", _ => null }; } private static string? NormalizeMediaTypeFilter(string? value) { return value?.Trim().ToLowerInvariant() switch { "movie" => "movie", "tv" or "series" or "show" => "tv", "multi" or "" or null => "multi", _ => null }; } private IActionResult EmbeddedFile(string resourceSuffix, string contentType) { Response.Headers.CacheControl = "no-store, max-age=0"; var assembly = typeof(RequestController).Assembly; var resource = assembly.GetManifestResourceNames() .FirstOrDefault(name => name.EndsWith(resourceSuffix, StringComparison.Ordinal)); if (resource is null) { return NotFound(); } using var stream = assembly.GetManifestResourceStream(resource); if (stream is null) { return NotFound(); } using var reader = new StreamReader(stream); return Content(reader.ReadToEnd(), contentType); } }