diff --git a/.gitignore b/.gitignore index 4090514..4eb05f2 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,13 @@ __pycache__/ *.py[cod] .venv/ venv/ + +bin/ +obj/ +.vs/ +artifacts/ +*.user + + +release/stage/ + diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..fc37f5e --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,7 @@ + + + 1.0.0.0 + 1.0.0.0 + 1.0.0.0 + + diff --git a/Jellyfin.Plugin.Request.sln b/Jellyfin.Plugin.Request.sln new file mode 100644 index 0000000..0448676 --- /dev/null +++ b/Jellyfin.Plugin.Request.sln @@ -0,0 +1,18 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.Request", "Jellyfin.Plugin.Request\Jellyfin.Plugin.Request.csproj", "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/Jellyfin.Plugin.Request/Api/CreateRequestDto.cs b/Jellyfin.Plugin.Request/Api/CreateRequestDto.cs new file mode 100644 index 0000000..05a5a76 --- /dev/null +++ b/Jellyfin.Plugin.Request/Api/CreateRequestDto.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace Jellyfin.Plugin.Request.Api; + +/// +/// Body for creating a media request. +/// +public sealed class CreateRequestDto +{ + /// + /// Gets or sets the media type (movie or tv). + /// + [Required] + public string MediaType { get; set; } = string.Empty; + + /// + /// Gets or sets the TMDB identifier. + /// + [Range(1, int.MaxValue)] + public int TmdbId { get; set; } + + /// + /// Gets or sets optional season numbers for TV. + /// Null or empty with true requests everything. + /// + public List? Seasons { get; set; } + + /// + /// Gets or sets a value indicating whether all seasons are requested. + /// + public bool AllSeasons { get; set; } = true; +} + +/// +/// Optional admin note body for status transitions. +/// +public sealed class AdminNoteDto +{ + /// + /// Gets or sets an optional administrator note. + /// + public string? AdminNote { get; set; } +} diff --git a/Jellyfin.Plugin.Request/Api/RequestController.cs b/Jellyfin.Plugin.Request/Api/RequestController.cs new file mode 100644 index 0000000..bedd4a4 --- /dev/null +++ b/Jellyfin.Plugin.Request/Api/RequestController.cs @@ -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; + +/// +/// 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(); + return Ok(new + { + isConfigured = !string.IsNullOrWhiteSpace(config.TmdbApiKey), + requestSubmissionEnabled = config.EnableRequestSubmission, + allowSeasonSelection = config.AllowSeasonSelection + }); + } + + /// + /// Serves the standalone request page. + /// + /// HTML page. + [HttpGet("Page")] + [AllowAnonymous] + public IActionResult Page() + { + return EmbeddedFile("Web.requestPage.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." }); + } + + 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? 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); + } + + /// + /// 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(); + } + + 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> 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 existing, + Guid userId, + string mediaType, + int tmdbId, + bool allSeasons, + List? 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); + } +} diff --git a/Jellyfin.Plugin.Request/Configuration/PluginConfiguration.cs b/Jellyfin.Plugin.Request/Configuration/PluginConfiguration.cs new file mode 100644 index 0000000..2879324 --- /dev/null +++ b/Jellyfin.Plugin.Request/Configuration/PluginConfiguration.cs @@ -0,0 +1,25 @@ +using MediaBrowser.Model.Plugins; + +namespace Jellyfin.Plugin.Request.Configuration; + +/// +/// Plugin configuration for the Request plugin. +/// +public sealed class PluginConfiguration : BasePluginConfiguration +{ + /// + /// Gets or sets the TMDB API key. Used only server-side. + /// + public string TmdbApiKey { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether users may submit requests. + /// + public bool EnableRequestSubmission { get; set; } + + /// + /// Gets or sets a value indicating whether users may request individual TV seasons. + /// When false, TV requests always cover all seasons. + /// + public bool AllowSeasonSelection { get; set; } = true; +} diff --git a/Jellyfin.Plugin.Request/Configuration/configPage.html b/Jellyfin.Plugin.Request/Configuration/configPage.html new file mode 100644 index 0000000..0b934b9 --- /dev/null +++ b/Jellyfin.Plugin.Request/Configuration/configPage.html @@ -0,0 +1,78 @@ + + + + Request + + + + + + + + Request + + + + TMDB API key + + + Create a free key at themoviedb.org. Stored server-side only; never sent to browsers by plugin APIs. + + + + + Enable request submission + + + Leave disabled until TMDB search is configured and tested. + + + + Allow users to request individual TV seasons + + + When unchecked, TV requests always cover all seasons. + + + + + Save + + + + + + + + + diff --git a/Jellyfin.Plugin.Request/Hosting/WebNavInjector.cs b/Jellyfin.Plugin.Request/Hosting/WebNavInjector.cs new file mode 100644 index 0000000..fe8501a --- /dev/null +++ b/Jellyfin.Plugin.Request/Hosting/WebNavInjector.cs @@ -0,0 +1,124 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.Request.Hosting; + +/// +/// Ensures jellyfin-web index.html loads the Request nav loader script. +/// +public sealed class WebNavInjector : IHostedService +{ + private const string LoaderSrc = "/Requests/Assets/nav-loader.js"; + private const string MarkerStart = ""; + private const string MarkerEnd = ""; + + private readonly IServerApplicationPaths _applicationPaths; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Server application paths. + /// Logger. + public WebNavInjector(IServerApplicationPaths applicationPaths, ILogger logger) + { + _applicationPaths = applicationPaths; + _logger = logger; + } + + /// + public Task StartAsync(CancellationToken cancellationToken) + { + try + { + TryInject(); + } + catch (Exception ex) + { + _logger.LogWarning( + ex, + "Could not inject Request nav loader into jellyfin-web. Use scripts/install-web-loader.ps1 or .sh after ensuring index.html is writable."); + } + + return Task.CompletedTask; + } + + /// + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + private void TryInject() + { + var indexPath = ResolveIndexHtmlPath(); + if (indexPath is null) + { + _logger.LogWarning("Could not locate jellyfin-web index.html for Request nav injection."); + return; + } + + if (!File.Exists(indexPath)) + { + _logger.LogWarning("jellyfin-web index.html was not found at {Path}", indexPath); + return; + } + + var html = File.ReadAllText(indexPath); + if (html.Contains(LoaderSrc, StringComparison.Ordinal)) + { + _logger.LogInformation("Request nav loader already present in {Path}", indexPath); + return; + } + + var block = $"{MarkerStart}{Environment.NewLine}{Environment.NewLine}{MarkerEnd}"; + string updated; + var bodyIndex = html.LastIndexOf("