feat(repo): add request plugin with jellyfin catalog manifest
Ship the plugin sources, release zip, and SeerrFin-style manifest.json so Jellyfin can install from the Gitea raw repository URL. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a1960d860
commit
bf6cd4540f
30 files changed
+3096
No files matched your search
@@ -0,0 +1,44 @@
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Jellyfin.Plugin.Request.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Body for creating a media request.
|
||||
/// </summary>
|
||||
public sealed class CreateRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the media type (<c>movie</c> or <c>tv</c>).
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string MediaType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the TMDB identifier.
|
||||
/// </summary>
|
||||
[Range(1, int.MaxValue)]
|
||||
public int TmdbId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional season numbers for TV.
|
||||
/// Null or empty with <see cref="AllSeasons"/> true requests everything.
|
||||
/// </summary>
|
||||
public List<int>? Seasons { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether all seasons are requested.
|
||||
/// </summary>
|
||||
public bool AllSeasons { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optional admin note body for status transitions.
|
||||
/// </summary>
|
||||
public sealed class AdminNoteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets an optional administrator note.
|
||||
/// </summary>
|
||||
public string? AdminNote { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
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.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();
|
||||
return Ok(new
|
||||
{
|
||||
isConfigured = !string.IsNullOrWhiteSpace(config.TmdbApiKey),
|
||||
requestSubmissionEnabled = config.EnableRequestSubmission,
|
||||
allowSeasonSelection = config.AllowSeasonSelection
|
||||
});
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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." });
|
||||
}
|
||||
|
||||
var userId = GetUserId();
|
||||
if (userId == Guid.Empty)
|
||||
{
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
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 CreatedAtAction(nameof(List), new { id = request.Id }, 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();
|
||||
}
|
||||
|
||||
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var isAdmin = IsAdministrator(userId);
|
||||
if (!isAdmin && (existing.RequestedByUserId != userId || existing.Status != RequestStatus.Pending))
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
if (!IsAdministrator(userId))
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
var raw = User.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
?? User.FindFirstValue("sub")
|
||||
?? User.FindFirstValue("Jellyfin-UserId");
|
||||
return Guid.TryParse(raw, out var userId) ? userId : 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user