Expose isAdmin from Status, show Admin queue controls only for administrators, and return clear 403/404 messages for approve/reject/fulfill/delete. Co-authored-by: Cursor <cursoragent@cursor.com>
540 lines
18 KiB
C#
540 lines
18 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// REST API for searching media and managing the local request queue.
|
|
/// </summary>
|
|
[ApiController]
|
|
[Authorize]
|
|
[Route("Requests")]
|
|
public sealed class RequestController : ControllerBase
|
|
{
|
|
private readonly RequestStore _store;
|
|
private readonly TmdbClient _tmdbClient;
|
|
private readonly IUserManager _userManager;
|
|
private readonly ILogger<RequestController> _logger;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="RequestController"/> class.
|
|
/// </summary>
|
|
/// <param name="store">Request store.</param>
|
|
/// <param name="tmdbClient">TMDB client.</param>
|
|
/// <param name="userManager">User manager.</param>
|
|
/// <param name="logger">Logger.</param>
|
|
public RequestController(
|
|
RequestStore store,
|
|
TmdbClient tmdbClient,
|
|
IUserManager userManager,
|
|
ILogger<RequestController> logger)
|
|
{
|
|
_store = store;
|
|
_tmdbClient = tmdbClient;
|
|
_userManager = userManager;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns non-secret plugin status for the request UI.
|
|
/// </summary>
|
|
/// <returns>Status payload.</returns>
|
|
[HttpGet("Status")]
|
|
[AllowAnonymous]
|
|
public ActionResult<object> 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)
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Serves the standalone request page.
|
|
/// </summary>
|
|
/// <returns>HTML page.</returns>
|
|
[HttpGet("Page")]
|
|
[AllowAnonymous]
|
|
public IActionResult Page()
|
|
{
|
|
return EmbeddedFile("Web.requestPage.html", "text/html; charset=utf-8");
|
|
}
|
|
|
|
/// <summary>
|
|
/// File Transformation endpoint: injects nav-loader.js into jellyfin-web index.html.
|
|
/// Must stay anonymous because File Transformation calls it without auth.
|
|
/// </summary>
|
|
/// <param name="payload">Current file contents.</param>
|
|
/// <returns>Transformed HTML body.</returns>
|
|
[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");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Serves plugin web assets.
|
|
/// </summary>
|
|
/// <param name="assetName">Asset file name.</param>
|
|
/// <returns>Asset response.</returns>
|
|
[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!);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Searches TMDB for movies or TV shows.
|
|
/// </summary>
|
|
/// <param name="query">Search query.</param>
|
|
/// <param name="type">movie, tv, or multi.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Search results.</returns>
|
|
[HttpGet("Search")]
|
|
public async Task<ActionResult<IReadOnlyList<TmdbSearchItem>>> 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 });
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns TMDB details for a movie or TV show.
|
|
/// </summary>
|
|
/// <param name="type">movie or tv.</param>
|
|
/// <param name="tmdbId">TMDB identifier.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Media detail.</returns>
|
|
[HttpGet("Media/{type}/{tmdbId:int}")]
|
|
public async Task<ActionResult<TmdbMediaDetail>> 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 });
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Lists requests visible to the current user.
|
|
/// </summary>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Request list.</returns>
|
|
[HttpGet]
|
|
public async Task<ActionResult<IReadOnlyList<MediaRequest>>> 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());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new media request.
|
|
/// </summary>
|
|
/// <param name="body">Request body.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Created request.</returns>
|
|
[HttpPost]
|
|
public async Task<ActionResult<MediaRequest>> 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 || body.TmdbId <= 0)
|
|
{
|
|
return BadRequest(new { message = "mediaType must be movie or tv and tmdbId must be positive." });
|
|
}
|
|
|
|
var allSeasons = body.AllSeasons;
|
|
List<int>? 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,
|
|
Title = detail.Title,
|
|
Year = detail.Year,
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Approves a request.
|
|
/// </summary>
|
|
/// <param name="id">Request identifier.</param>
|
|
/// <param name="body">Optional note.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Updated request.</returns>
|
|
[HttpPost("{id:guid}/approve")]
|
|
public Task<ActionResult<MediaRequest>> Approve(
|
|
Guid id,
|
|
[FromBody] AdminNoteDto? body,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
return SetStatusAsync(id, RequestStatus.Approved, body?.AdminNote, cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Rejects a request.
|
|
/// </summary>
|
|
/// <param name="id">Request identifier.</param>
|
|
/// <param name="body">Optional note.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Updated request.</returns>
|
|
[HttpPost("{id:guid}/reject")]
|
|
public Task<ActionResult<MediaRequest>> Reject(
|
|
Guid id,
|
|
[FromBody] AdminNoteDto? body,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
return SetStatusAsync(id, RequestStatus.Rejected, body?.AdminNote, cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Marks a request as fulfilled.
|
|
/// </summary>
|
|
/// <param name="id">Request identifier.</param>
|
|
/// <param name="body">Optional note.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Updated request.</returns>
|
|
[HttpPost("{id:guid}/fulfill")]
|
|
public Task<ActionResult<MediaRequest>> Fulfill(
|
|
Guid id,
|
|
[FromBody] AdminNoteDto? body,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
return SetStatusAsync(id, RequestStatus.Fulfilled, body?.AdminNote, cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deletes a request.
|
|
/// </summary>
|
|
/// <param name="id">Request identifier.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>No content when deleted.</returns>
|
|
[HttpDelete("{id:guid}")]
|
|
public async Task<IActionResult> 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<ActionResult<MediaRequest>> 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<MediaRequest> existing,
|
|
Guid userId,
|
|
string mediaType,
|
|
int tmdbId,
|
|
bool allSeasons,
|
|
List<int>? seasons)
|
|
{
|
|
foreach (var item in existing)
|
|
{
|
|
if (item.RequestedByUserId != userId
|
|
|| !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 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);
|
|
}
|
|
}
|