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:
Michael SloanandCursor committed 2026-08-02 16:31:26 -04:00
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);
}
}
@@ -0,0 +1,25 @@
using MediaBrowser.Model.Plugins;
namespace Jellyfin.Plugin.Request.Configuration;
/// <summary>
/// Plugin configuration for the Request plugin.
/// </summary>
public sealed class PluginConfiguration : BasePluginConfiguration
{
/// <summary>
/// Gets or sets the TMDB API key. Used only server-side.
/// </summary>
public string TmdbApiKey { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether users may submit requests.
/// </summary>
public bool EnableRequestSubmission { get; set; }
/// <summary>
/// Gets or sets a value indicating whether users may request individual TV seasons.
/// When false, TV requests always cover all seasons.
/// </summary>
public bool AllowSeasonSelection { get; set; } = true;
}
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<title>Request</title>
</head>
<body>
<div id="RequestConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-checkbox">
<div data-role="content">
<div class="content-primary">
<form id="RequestConfigForm">
<div class="sectionTitleContainer flex align-items-center">
<h2 class="sectionTitle">Request</h2>
</div>
<div class="verticalSection">
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="TmdbApiKey">TMDB API key</label>
<input is="emby-input" type="password" id="TmdbApiKey" autocomplete="off" />
<div class="fieldDescription">
Create a free key at themoviedb.org. Stored server-side only; never sent to browsers by plugin APIs.
</div>
</div>
<label class="checkboxContainer">
<input is="emby-checkbox" type="checkbox" id="EnableRequestSubmission" />
<span>Enable request submission</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Leave disabled until TMDB search is configured and tested.
</div>
<label class="checkboxContainer">
<input is="emby-checkbox" type="checkbox" id="AllowSeasonSelection" />
<span>Allow users to request individual TV seasons</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
When unchecked, TV requests always cover all seasons.
</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block">
<span>Save</span>
</button>
</div>
</form>
</div>
</div>
<script type="text/javascript">
(() => {
const pluginId = "11c08950-c4bb-484d-89ff-205b3724416b";
const page = document.querySelector("#RequestConfigPage");
const form = page.querySelector("#RequestConfigForm");
page.addEventListener("pageshow", () => {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(pluginId).then((config) => {
page.querySelector("#TmdbApiKey").value = config.TmdbApiKey || "";
page.querySelector("#EnableRequestSubmission").checked = !!config.EnableRequestSubmission;
page.querySelector("#AllowSeasonSelection").checked = config.AllowSeasonSelection !== false;
Dashboard.hideLoadingMsg();
});
});
form.addEventListener("submit", (event) => {
event.preventDefault();
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(pluginId).then((config) => {
config.TmdbApiKey = page.querySelector("#TmdbApiKey").value.trim();
config.EnableRequestSubmission = page.querySelector("#EnableRequestSubmission").checked;
config.AllowSeasonSelection = page.querySelector("#AllowSeasonSelection").checked;
return ApiClient.updatePluginConfiguration(pluginId, config);
}).then(() => {
Dashboard.processPluginConfigurationUpdateResult();
});
return false;
});
})();
</script>
</div>
</body>
</html>
@@ -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;
/// <summary>
/// Ensures jellyfin-web index.html loads the Request nav loader script.
/// </summary>
public sealed class WebNavInjector : IHostedService
{
private const string LoaderSrc = "/Requests/Assets/nav-loader.js";
private const string MarkerStart = "<!-- jellyfin-plugin-request-nav-start -->";
private const string MarkerEnd = "<!-- jellyfin-plugin-request-nav-end -->";
private readonly IServerApplicationPaths _applicationPaths;
private readonly ILogger<WebNavInjector> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="WebNavInjector"/> class.
/// </summary>
/// <param name="applicationPaths">Server application paths.</param>
/// <param name="logger">Logger.</param>
public WebNavInjector(IServerApplicationPaths applicationPaths, ILogger<WebNavInjector> logger)
{
_applicationPaths = applicationPaths;
_logger = logger;
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
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}<script src=\"{LoaderSrc}\" defer></script>{Environment.NewLine}{MarkerEnd}";
string updated;
var bodyIndex = html.LastIndexOf("</body>", StringComparison.OrdinalIgnoreCase);
if (bodyIndex >= 0)
{
updated = html.Insert(bodyIndex, block + Environment.NewLine);
}
else
{
updated = html + Environment.NewLine + block + Environment.NewLine;
}
File.WriteAllText(indexPath, updated);
_logger.LogInformation("Injected Request nav loader into {Path}", indexPath);
}
private string? ResolveIndexHtmlPath()
{
var webPath = _applicationPaths.WebPath;
if (!string.IsNullOrWhiteSpace(webPath))
{
var candidate = Path.Combine(webPath, "index.html");
if (File.Exists(candidate))
{
return candidate;
}
}
string[] fallbacks =
[
"/usr/share/jellyfin/web/index.html",
"/usr/lib/jellyfin/bin/jellyfin-web/index.html",
Path.Combine(AppContext.BaseDirectory, "jellyfin-web", "index.html")
];
foreach (var path in fallbacks)
{
if (File.Exists(path))
{
return path;
}
}
return null;
}
}
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<RootNamespace>Jellyfin.Plugin.Request</RootNamespace>
<AssemblyName>Jellyfin.Plugin.Request</AssemblyName>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<Nullable>enable</Nullable>
<AnalysisMode>Default</AnalysisMode>
<CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
<NoWarn>$(NoWarn);CA1002;CA2227;CA2007;CA1001</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="10.11.3">
<PrivateAssets>all</PrivateAssets>
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="Jellyfin.Model" Version="10.11.3">
<PrivateAssets>all</PrivateAssets>
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<None Remove="Configuration\configPage.html" />
<None Remove="Web\**\*" />
<EmbeddedResource Include="Configuration\configPage.html" />
<EmbeddedResource Include="Web\**\*" />
</ItemGroup>
</Project>
+57
View File
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Jellyfin.Plugin.Request.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
namespace Jellyfin.Plugin.Request;
/// <summary>
/// Request plugin entry point.
/// </summary>
public sealed class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{
/// <summary>
/// Initializes a new instance of the <see cref="Plugin"/> class.
/// </summary>
/// <param name="applicationPaths">Application paths.</param>
/// <param name="xmlSerializer">XML serializer.</param>
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
: base(applicationPaths, xmlSerializer)
{
Instance = this;
}
/// <inheritdoc />
public override string Name => "Request";
/// <inheritdoc />
public override string Description => "Local movie and TV request queue with a Request tab in Jellyfin Web.";
/// <inheritdoc />
public override Guid Id => Guid.Parse("11c08950-c4bb-484d-89ff-205b3724416b");
/// <summary>
/// Gets the plugin singleton instance.
/// </summary>
public static Plugin? Instance { get; private set; }
/// <inheritdoc />
public IEnumerable<PluginPageInfo> GetPages()
{
return
[
new PluginPageInfo
{
Name = Name,
EmbeddedResourcePath = string.Format(
CultureInfo.InvariantCulture,
"{0}.Configuration.configPage.html",
GetType().Namespace)
}
];
}
}
@@ -0,0 +1,28 @@
using Jellyfin.Plugin.Request.Hosting;
using Jellyfin.Plugin.Request.Storage;
using Jellyfin.Plugin.Request.Tmdb;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using Microsoft.Extensions.DependencyInjection;
namespace Jellyfin.Plugin.Request;
/// <summary>
/// Registers plugin services with the Jellyfin DI container.
/// </summary>
public sealed class PluginServiceRegistrator : IPluginServiceRegistrator
{
/// <inheritdoc />
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
{
serviceCollection.AddSingleton<RequestStore>();
serviceCollection.AddHttpClient(TmdbClient.HttpClientName, client =>
{
client.BaseAddress = new System.Uri("https://api.themoviedb.org/3/");
client.Timeout = System.TimeSpan.FromSeconds(30);
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
});
serviceCollection.AddSingleton<TmdbClient>();
serviceCollection.AddHostedService<WebNavInjector>();
}
}
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.Request.Storage;
/// <summary>
/// A user-submitted movie or TV request.
/// </summary>
public sealed class MediaRequest
{
/// <summary>
/// Gets or sets the request identifier.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the media type (<c>movie</c> or <c>tv</c>).
/// </summary>
public string MediaType { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the TMDB identifier.
/// </summary>
public int TmdbId { get; set; }
/// <summary>
/// Gets or sets the display title.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the release year when known.
/// </summary>
public int? Year { get; set; }
/// <summary>
/// Gets or sets the TMDB poster path.
/// </summary>
public string? PosterPath { get; set; }
/// <summary>
/// Gets or sets season numbers for TV, or null / empty for all seasons.
/// </summary>
public List<int>? Seasons { get; set; }
/// <summary>
/// Gets or sets a value indicating whether all seasons were requested.
/// </summary>
public bool AllSeasons { get; set; }
/// <summary>
/// Gets or sets the requesting user's identifier.
/// </summary>
public Guid RequestedByUserId { get; set; }
/// <summary>
/// Gets or sets the requesting user's display name.
/// </summary>
public string RequestedByName { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the UTC creation timestamp.
/// </summary>
public DateTime CreatedAtUtc { get; set; }
/// <summary>
/// Gets or sets the request status.
/// </summary>
public RequestStatus Status { get; set; }
/// <summary>
/// Gets or sets an optional administrator note.
/// </summary>
public string? AdminNote { get; set; }
}
@@ -0,0 +1,27 @@
namespace Jellyfin.Plugin.Request.Storage;
/// <summary>
/// Lifecycle status for a media request.
/// </summary>
public enum RequestStatus
{
/// <summary>
/// Waiting for administrator review.
/// </summary>
Pending = 0,
/// <summary>
/// Approved by an administrator.
/// </summary>
Approved = 1,
/// <summary>
/// Rejected by an administrator.
/// </summary>
Rejected = 2,
/// <summary>
/// Marked fulfilled by an administrator.
/// </summary>
Fulfilled = 3
}
@@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Request.Storage;
/// <summary>
/// Thread-safe JSON persistence for media requests.
/// </summary>
public sealed class RequestStore
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
private readonly ILogger<RequestStore> _logger;
private readonly string _filePath;
private readonly SemaphoreSlim _gate = new(1, 1);
/// <summary>
/// Initializes a new instance of the <see cref="RequestStore"/> class.
/// </summary>
/// <param name="applicationPaths">Application paths.</param>
/// <param name="logger">Logger.</param>
public RequestStore(IApplicationPaths applicationPaths, ILogger<RequestStore> logger)
{
_logger = logger;
var directory = Path.Combine(applicationPaths.PluginConfigurationsPath, "Jellyfin.Plugin.Request");
Directory.CreateDirectory(directory);
_filePath = Path.Combine(directory, "requests.json");
}
/// <summary>
/// Loads all requests.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Request list.</returns>
public async Task<IReadOnlyList<MediaRequest>> GetAllAsync(CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
return await ReadUnlockedAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Adds a request and persists it.
/// </summary>
/// <param name="request">Request to add.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The stored request.</returns>
public async Task<MediaRequest> AddAsync(MediaRequest request, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var items = await ReadUnlockedAsync(cancellationToken).ConfigureAwait(false);
items.Add(request);
await WriteUnlockedAsync(items, cancellationToken).ConfigureAwait(false);
return request;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Updates an existing request.
/// </summary>
/// <param name="request">Updated request.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>True when updated.</returns>
public async Task<bool> UpdateAsync(MediaRequest request, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var items = await ReadUnlockedAsync(cancellationToken).ConfigureAwait(false);
var index = items.FindIndex(item => item.Id == request.Id);
if (index < 0)
{
return false;
}
items[index] = request;
await WriteUnlockedAsync(items, cancellationToken).ConfigureAwait(false);
return true;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Deletes a request by identifier.
/// </summary>
/// <param name="id">Request identifier.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The deleted request, or null.</returns>
public async Task<MediaRequest?> DeleteAsync(Guid id, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var items = await ReadUnlockedAsync(cancellationToken).ConfigureAwait(false);
var existing = items.FirstOrDefault(item => item.Id == id);
if (existing is null)
{
return null;
}
items.Remove(existing);
await WriteUnlockedAsync(items, cancellationToken).ConfigureAwait(false);
return existing;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Finds a request by identifier.
/// </summary>
/// <param name="id">Request identifier.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The request, or null.</returns>
public async Task<MediaRequest?> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
var items = await GetAllAsync(cancellationToken).ConfigureAwait(false);
return items.FirstOrDefault(item => item.Id == id);
}
private async Task<List<MediaRequest>> ReadUnlockedAsync(CancellationToken cancellationToken)
{
if (!File.Exists(_filePath))
{
return [];
}
try
{
await using var stream = File.OpenRead(_filePath);
var items = await JsonSerializer.DeserializeAsync<List<MediaRequest>>(stream, JsonOptions, cancellationToken)
.ConfigureAwait(false);
return items ?? [];
}
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
{
_logger.LogError(ex, "Failed to read request store at {Path}", _filePath);
return [];
}
}
private async Task WriteUnlockedAsync(List<MediaRequest> items, CancellationToken cancellationToken)
{
var directory = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
var tempPath = _filePath + ".tmp";
await using (var stream = File.Create(tempPath))
{
await JsonSerializer.SerializeAsync(stream, items, JsonOptions, cancellationToken).ConfigureAwait(false);
}
File.Move(tempPath, _filePath, overwrite: true);
}
}
+190
View File
@@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Jellyfin.Plugin.Request.Tmdb;
/// <summary>
/// Server-side TMDB API client.
/// </summary>
public sealed class TmdbClient
{
/// <summary>
/// Named HTTP client for TMDB.
/// </summary>
public const string HttpClientName = "Tmdb";
private readonly IHttpClientFactory _httpClientFactory;
/// <summary>
/// Initializes a new instance of the <see cref="TmdbClient"/> class.
/// </summary>
/// <param name="httpClientFactory">HTTP client factory.</param>
public TmdbClient(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
/// <summary>
/// Searches TMDB for movies or TV shows.
/// </summary>
/// <param name="query">Search query.</param>
/// <param name="mediaType">movie, tv, or multi.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Search results.</returns>
public async Task<IReadOnlyList<TmdbSearchItem>> SearchAsync(
string query,
string mediaType,
CancellationToken cancellationToken)
{
var apiKey = RequireApiKey();
var path = mediaType switch
{
"movie" => "search/movie",
"tv" => "search/tv",
_ => "search/multi"
};
var url = $"{path}?api_key={Uri.EscapeDataString(apiKey)}&query={Uri.EscapeDataString(query)}&include_adult=false";
var client = _httpClientFactory.CreateClient(HttpClientName);
var response = await client.GetFromJsonAsync<TmdbSearchResponse>(url, cancellationToken).ConfigureAwait(false);
if (response?.Results is null)
{
return [];
}
return response.Results
.Select(result => MapSearchResult(result, mediaType))
.Where(item => item is not null)
.Cast<TmdbSearchItem>()
.Take(40)
.ToList();
}
/// <summary>
/// Loads movie or TV details from TMDB.
/// </summary>
/// <param name="mediaType">movie or tv.</param>
/// <param name="tmdbId">TMDB identifier.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Media detail, or null when not found.</returns>
public async Task<TmdbMediaDetail?> GetDetailsAsync(
string mediaType,
int tmdbId,
CancellationToken cancellationToken)
{
var apiKey = RequireApiKey();
var client = _httpClientFactory.CreateClient(HttpClientName);
if (mediaType.Equals("movie", StringComparison.OrdinalIgnoreCase))
{
var movie = await client.GetFromJsonAsync<TmdbMovieDetailResponse>(
$"movie/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
cancellationToken)
.ConfigureAwait(false);
if (movie is null)
{
return null;
}
return new TmdbMediaDetail
{
TmdbId = movie.Id,
MediaType = "movie",
Title = movie.Title ?? string.Empty,
Overview = movie.Overview,
Year = ParseYear(movie.ReleaseDate),
PosterPath = movie.PosterPath
};
}
if (mediaType.Equals("tv", StringComparison.OrdinalIgnoreCase))
{
var show = await client.GetFromJsonAsync<TmdbTvDetailResponse>(
$"tv/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
cancellationToken)
.ConfigureAwait(false);
if (show is null)
{
return null;
}
return new TmdbMediaDetail
{
TmdbId = show.Id,
MediaType = "tv",
Title = show.Name ?? string.Empty,
Overview = show.Overview,
Year = ParseYear(show.FirstAirDate),
PosterPath = show.PosterPath,
Seasons = show.Seasons
.Where(season => season.SeasonNumber > 0)
.Select(season => new TmdbSeasonInfo
{
SeasonNumber = season.SeasonNumber,
Name = season.Name ?? $"Season {season.SeasonNumber}",
EpisodeCount = season.EpisodeCount
})
.ToList()
};
}
throw new ArgumentException("mediaType must be movie or tv.", nameof(mediaType));
}
private static string RequireApiKey()
{
var apiKey = Plugin.Instance?.Configuration.TmdbApiKey?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new InvalidOperationException("TMDB API key is not configured.");
}
return apiKey;
}
private static TmdbSearchItem? MapSearchResult(TmdbRawResult result, string requestedType)
{
var type = requestedType is "movie" or "tv"
? requestedType
: result.MediaType?.ToLowerInvariant();
if (type is not ("movie" or "tv"))
{
return null;
}
var title = type == "movie" ? result.Title : result.Name;
if (string.IsNullOrWhiteSpace(title))
{
return null;
}
return new TmdbSearchItem
{
TmdbId = result.Id,
MediaType = type,
Title = title,
Overview = result.Overview,
Year = ParseYear(type == "movie" ? result.ReleaseDate : result.FirstAirDate),
PosterPath = result.PosterPath
};
}
private static int? ParseYear(string? date)
{
if (string.IsNullOrWhiteSpace(date) || date.Length < 4)
{
return null;
}
return int.TryParse(date.AsSpan(0, 4), NumberStyles.None, CultureInfo.InvariantCulture, out var year)
? year
: null;
}
}
+200
View File
@@ -0,0 +1,200 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Jellyfin.Plugin.Request.Tmdb;
/// <summary>
/// Normalized search hit returned to clients.
/// </summary>
public sealed class TmdbSearchItem
{
/// <summary>
/// Gets or sets the TMDB identifier.
/// </summary>
public int TmdbId { get; set; }
/// <summary>
/// Gets or sets the media type.
/// </summary>
public string MediaType { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the overview.
/// </summary>
public string? Overview { get; set; }
/// <summary>
/// Gets or sets the year.
/// </summary>
public int? Year { get; set; }
/// <summary>
/// Gets or sets the poster path.
/// </summary>
public string? PosterPath { get; set; }
/// <summary>
/// Gets the full poster URL when a path is present.
/// </summary>
public string? PosterUrl => string.IsNullOrEmpty(PosterPath)
? null
: $"https://image.tmdb.org/t/p/w342{PosterPath}";
}
/// <summary>
/// Normalized media detail returned to clients.
/// </summary>
public sealed class TmdbMediaDetail
{
/// <summary>
/// Gets or sets the TMDB identifier.
/// </summary>
public int TmdbId { get; set; }
/// <summary>
/// Gets or sets the media type.
/// </summary>
public string MediaType { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the overview.
/// </summary>
public string? Overview { get; set; }
/// <summary>
/// Gets or sets the year.
/// </summary>
public int? Year { get; set; }
/// <summary>
/// Gets or sets the poster path.
/// </summary>
public string? PosterPath { get; set; }
/// <summary>
/// Gets the full poster URL when a path is present.
/// </summary>
public string? PosterUrl => string.IsNullOrEmpty(PosterPath)
? null
: $"https://image.tmdb.org/t/p/w500{PosterPath}";
/// <summary>
/// Gets or sets TV seasons when applicable.
/// </summary>
public List<TmdbSeasonInfo> Seasons { get; set; } = [];
}
/// <summary>
/// Season summary for TV detail views.
/// </summary>
public sealed class TmdbSeasonInfo
{
/// <summary>
/// Gets or sets the season number.
/// </summary>
public int SeasonNumber { get; set; }
/// <summary>
/// Gets or sets the season name.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the episode count.
/// </summary>
public int EpisodeCount { get; set; }
}
internal sealed class TmdbSearchResponse
{
[JsonPropertyName("results")]
public List<TmdbRawResult> Results { get; set; } = [];
}
internal sealed class TmdbRawResult
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("media_type")]
public string? MediaType { get; set; }
[JsonPropertyName("title")]
public string? Title { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("overview")]
public string? Overview { get; set; }
[JsonPropertyName("poster_path")]
public string? PosterPath { get; set; }
[JsonPropertyName("release_date")]
public string? ReleaseDate { get; set; }
[JsonPropertyName("first_air_date")]
public string? FirstAirDate { get; set; }
}
internal sealed class TmdbMovieDetailResponse
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("title")]
public string? Title { get; set; }
[JsonPropertyName("overview")]
public string? Overview { get; set; }
[JsonPropertyName("poster_path")]
public string? PosterPath { get; set; }
[JsonPropertyName("release_date")]
public string? ReleaseDate { get; set; }
}
internal sealed class TmdbTvDetailResponse
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("overview")]
public string? Overview { get; set; }
[JsonPropertyName("poster_path")]
public string? PosterPath { get; set; }
[JsonPropertyName("first_air_date")]
public string? FirstAirDate { get; set; }
[JsonPropertyName("seasons")]
public List<TmdbSeasonRaw> Seasons { get; set; } = [];
}
internal sealed class TmdbSeasonRaw
{
[JsonPropertyName("season_number")]
public int SeasonNumber { get; set; }
[JsonPropertyName("name")]
public string? Name { get; set; }
[JsonPropertyName("episode_count")]
public int EpisodeCount { get; set; }
}
+239
View File
@@ -0,0 +1,239 @@
(() => {
"use strict";
const REQUEST_URL = "/Requests/Page";
const STYLE_ID = "jellyfin-plugin-request-nav-style";
function textOf(node) {
return [
node?.textContent,
node?.getAttribute?.("aria-label"),
node?.getAttribute?.("title"),
node?.getAttribute?.("data-title")
].filter(Boolean).join(" ").replace(/\s+/g, " ").trim().toLowerCase();
}
function ensureStyle() {
if (document.getElementById(STYLE_ID)) {
return;
}
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = ".jf-request-menu-item{align-items:center;color:inherit;display:flex!important;gap:1rem;min-height:3rem;padding:.75rem 1.25rem;text-decoration:none}.jf-request-menu-item:hover,.jf-request-menu-item:focus,.jf-request-tab:hover,.jf-request-tab:focus{color:#00a4dc;text-decoration:none}.jf-request-menu-icon{align-items:center;display:inline-flex;font-size:1.45rem;justify-content:center;line-height:1;min-width:1.5rem}.jf-request-menu-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.jf-request-tab{align-items:center;color:inherit;display:inline-flex;text-decoration:none}";
document.head.appendChild(style);
}
function controlsIn(container) {
return Array.from(container.querySelectorAll("a, button, [role='button'], [role='menuitem'], [role='link']"));
}
function openRequestPage(event) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation?.();
window.location.assign(REQUEST_URL);
}
function wireLink(link) {
link.href = REQUEST_URL;
link.addEventListener("click", openRequestPage, true);
return link;
}
function labelMatches(node, labels) {
const label = textOf(node);
return labels.some((value) => label === value || label.includes(value));
}
function isDrawerElement(node) {
return Boolean(node?.closest?.(".mainDrawer,.mainDrawer-scrollContainer,.drawerContent,.MuiDrawer-paper"));
}
function sideMenuContainers() {
const selectors = [
".mainDrawer-scrollContainer",
".mainDrawer .scrollContainer",
".drawerContent",
".navMenu",
".MuiDrawer-paper"
];
const found = new Set();
for (const selector of selectors) {
for (const candidate of document.querySelectorAll(selector)) {
if (candidate.classList?.contains("mainDrawerHandle")) {
continue;
}
const labels = controlsIn(candidate).map(textOf);
const hasNormalNav = labels.includes("home")
|| labels.includes("favorites")
|| labels.includes("favourites")
|| labels.some((label) => label.includes("home"));
if (hasNormalNav) {
found.add(candidate);
}
}
}
return Array.from(found);
}
function topNavContainers() {
const found = new Set();
const selectors = [
".sectionTabs",
".emby-tabs",
".tabs",
".headerTabs",
".viewMenuBar",
".skinHeader .tabs"
];
for (const selector of selectors) {
for (const candidate of document.querySelectorAll(selector)) {
if (isDrawerElement(candidate)) {
continue;
}
const controls = controlsIn(candidate);
const hasHome = controls.some((item) => labelMatches(item, ["home"]));
const hasFavorites = controls.some((item) => labelMatches(item, ["favorites", "favourites"]));
if (hasHome && hasFavorites) {
found.add(candidate);
}
}
}
for (const home of controlsIn(document).filter((item) => !isDrawerElement(item) && labelMatches(item, ["home"]))) {
let candidate = home.parentElement;
for (let depth = 0; candidate && depth < 4; depth += 1, candidate = candidate.parentElement) {
const controls = controlsIn(candidate);
const hasFavorites = controls.some((item) => labelMatches(item, ["favorites", "favourites"]));
if (hasFavorites && controls.length <= 12) {
found.add(candidate);
break;
}
}
}
return Array.from(found).sort((left, right) => controlsIn(left).length - controlsIn(right).length);
}
function createMenuItem(reference) {
const link = document.createElement("a");
link.className = "jf-request-menu-item";
link.setAttribute("aria-label", "Requests");
wireLink(link);
const icon = document.createElement("span");
icon.className = "material-icons jf-request-menu-icon";
icon.setAttribute("aria-hidden", "true");
icon.textContent = "add_circle_outline";
const label = document.createElement("span");
label.className = "jf-request-menu-label";
label.textContent = "Requests";
link.append(icon, label);
const referenceClass = reference?.getAttribute("class");
if (referenceClass) {
link.setAttribute("class", `${referenceClass} jf-request-menu-item`);
}
const referenceRole = reference?.getAttribute("role");
if (referenceRole) {
link.setAttribute("role", referenceRole);
}
return link;
}
function createTopTab(reference) {
const tag = reference?.tagName?.toLowerCase() === "button" ? "button" : "a";
const link = document.createElement(tag);
link.className = "jf-request-tab";
link.textContent = "Request";
link.setAttribute("aria-label", "Request");
link.setAttribute("data-jellyfin-request", "request-tab");
if (tag === "button") {
link.type = "button";
}
wireLink(link);
const referenceClass = reference?.getAttribute("class");
if (referenceClass) {
link.setAttribute("class", `${referenceClass} jf-request-tab`);
}
const referenceRole = reference?.getAttribute("role");
if (referenceRole) {
link.setAttribute("role", referenceRole);
}
const referenceTabIndex = reference?.getAttribute("tabindex");
if (referenceTabIndex) {
link.setAttribute("tabindex", referenceTabIndex);
}
link.classList.remove("selected", "active", "is-active", "current");
link.removeAttribute("aria-selected");
return link;
}
function insertTopTab() {
ensureStyle();
const existingTabs = Array.from(document.querySelectorAll(".jf-request-tab"));
existingTabs.slice(1).forEach((node) => node.remove());
if (existingTabs.length > 0) {
return;
}
for (const container of topNavContainers()) {
const controls = controlsIn(container);
const after = controls.find((item) => /^(favorites|favourites)$/i.test(textOf(item)))
|| controls.find((item) => /^home$/i.test(textOf(item)) || textOf(item).includes("home"));
if (!after) {
continue;
}
after.insertAdjacentElement("afterend", createTopTab(after));
return;
}
}
function insertSideMenuItem() {
ensureStyle();
for (const container of sideMenuContainers()) {
if (container.querySelector(".jf-request-menu-item")) {
continue;
}
const controls = controlsIn(container);
const after = controls.find((item) => /^(favorites|favourites)$/i.test(textOf(item)))
|| controls.find((item) => /^home$/i.test(textOf(item)) || textOf(item).includes("home"))
|| controls[0];
if (!after) {
continue;
}
const link = createMenuItem(after);
if (after.parentElement === container) {
after.insertAdjacentElement("afterend", link);
} else {
after.parentElement?.insertAdjacentElement("afterend", link);
}
}
}
function insertEntries() {
insertTopTab();
insertSideMenuItem();
}
insertEntries();
setInterval(insertEntries, 1000);
new MutationObserver(insertEntries).observe(document.documentElement, { childList: true, subtree: true });
})();
+263
View File
@@ -0,0 +1,263 @@
:root {
--req-bg: #101010;
--req-panel: #1c1c1c;
--req-border: #2e2e2e;
--req-text: #eee;
--req-muted: #9a9a9a;
--req-accent: #00a4dc;
--req-danger: #e24040;
--req-ok: #4caf50;
--req-warn: #f0ad4e;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--req-bg);
color: var(--req-text);
font-family: Inherit, "Segoe UI", Roboto, sans-serif;
}
body {
padding: 1.25rem;
}
.req-header {
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: center;
justify-content: space-between;
margin-bottom: 1.25rem;
}
.req-title {
margin: 0;
font-size: 1.6rem;
font-weight: 600;
}
.req-tabs {
display: flex;
gap: 0.5rem;
}
.req-tab,
.req-btn,
.req-type-btn {
border: 1px solid var(--req-border);
background: var(--req-panel);
color: var(--req-text);
border-radius: 4px;
padding: 0.55rem 0.9rem;
cursor: pointer;
font: inherit;
}
.req-tab.active,
.req-type-btn.active,
.req-btn.primary {
background: var(--req-accent);
border-color: var(--req-accent);
color: #fff;
}
.req-btn.danger {
border-color: var(--req-danger);
color: #fff;
background: var(--req-danger);
}
.req-btn:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.req-search-row {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-bottom: 1rem;
}
.req-search-row input[type="search"] {
flex: 1 1 220px;
min-width: 180px;
padding: 0.7rem 0.85rem;
border-radius: 4px;
border: 1px solid var(--req-border);
background: var(--req-panel);
color: var(--req-text);
font: inherit;
}
.req-type-toggle {
display: flex;
gap: 0.35rem;
}
.req-status-banner {
margin-bottom: 1rem;
padding: 0.75rem 1rem;
border-radius: 4px;
background: #2a1f00;
border: 1px solid var(--req-warn);
color: #ffe8b0;
}
.req-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 1rem;
}
.req-card {
background: var(--req-panel);
border: 1px solid var(--req-border);
border-radius: 6px;
overflow: hidden;
cursor: pointer;
display: flex;
flex-direction: column;
}
.req-card:hover {
border-color: var(--req-accent);
}
.req-card img,
.req-detail-poster {
width: 100%;
aspect-ratio: 2 / 3;
object-fit: cover;
background: #000;
display: block;
}
.req-card-body,
.req-detail-meta {
padding: 0.65rem 0.75rem 0.85rem;
}
.req-card-title,
.req-detail-title {
font-weight: 600;
margin: 0 0 0.25rem;
}
.req-muted {
color: var(--req-muted);
font-size: 0.9rem;
}
.req-hidden {
display: none !important;
}
.req-detail {
display: grid;
grid-template-columns: 180px 1fr;
gap: 1.25rem;
background: var(--req-panel);
border: 1px solid var(--req-border);
border-radius: 8px;
padding: 1rem;
}
.req-detail-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 1rem;
}
.req-seasons {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 0.5rem;
margin-top: 0.75rem;
}
.req-season {
display: flex;
gap: 0.5rem;
align-items: center;
padding: 0.45rem 0.6rem;
border: 1px solid var(--req-border);
border-radius: 4px;
}
.req-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.req-list-item {
display: grid;
grid-template-columns: 64px 1fr auto;
gap: 0.85rem;
align-items: center;
background: var(--req-panel);
border: 1px solid var(--req-border);
border-radius: 6px;
padding: 0.65rem;
}
.req-list-item img {
width: 64px;
height: 96px;
object-fit: cover;
border-radius: 3px;
background: #000;
}
.req-badge {
display: inline-block;
padding: 0.15rem 0.45rem;
border-radius: 999px;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.req-badge.pending { background: #5a4500; color: #ffd978; }
.req-badge.approved { background: #0f3d1f; color: #8dffb0; }
.req-badge.rejected { background: #4a1212; color: #ff9d9d; }
.req-badge.fulfilled { background: #0a3345; color: #8ad7ff; }
.req-list-actions {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.req-message {
margin: 1rem 0;
color: var(--req-muted);
}
.req-error {
color: #ff8e8e;
}
@media (max-width: 700px) {
.req-detail {
grid-template-columns: 1fr;
}
.req-list-item {
grid-template-columns: 56px 1fr;
}
.req-list-actions {
grid-column: 1 / -1;
flex-direction: row;
flex-wrap: wrap;
}
}
+380
View File
@@ -0,0 +1,380 @@
(() => {
"use strict";
const API = "/Requests";
const state = {
mediaType: "multi",
status: null,
isAdmin: false,
detail: null,
requests: []
};
const els = {
statusBanner: document.getElementById("statusBanner"),
globalMessage: document.getElementById("globalMessage"),
searchInput: document.getElementById("searchInput"),
searchBtn: document.getElementById("searchBtn"),
results: document.getElementById("results"),
detail: document.getElementById("detail"),
mineList: document.getElementById("mineList"),
adminList: document.getElementById("adminList"),
adminTab: document.getElementById("adminTab"),
searchView: document.getElementById("searchView"),
mineView: document.getElementById("mineView"),
adminView: document.getElementById("adminView")
};
function authHeader() {
try {
const raw = localStorage.getItem("jellyfin_credentials");
const credentials = raw ? JSON.parse(raw) : null;
const server = credentials?.Servers?.find((item) => item.AccessToken) || credentials?.Servers?.[0];
const token = server?.AccessToken;
if (!token) {
return {};
}
return {
Authorization: `MediaBrowser Client="Request Plugin", Device="Browser", DeviceId="jellyfin-plugin-request", Version="1.0.0", Token="${token}"`,
"X-Emby-Token": token
};
} catch {
return {};
}
}
async function errorMessage(response) {
const text = await response.text();
try {
return JSON.parse(text).message || `${response.status} ${response.statusText}`;
} catch {
return text || `${response.status} ${response.statusText}`;
}
}
async function api(path, options = {}) {
const response = await fetch(`${API}${path}`, {
cache: "no-store",
...options,
headers: {
...authHeader(),
...(options.body ? { "Content-Type": "application/json" } : {}),
...(options.headers || {})
}
});
if (!response.ok) {
throw new Error(await errorMessage(response));
}
if (response.status === 204) {
return null;
}
const text = await response.text();
return text ? JSON.parse(text) : null;
}
function showMessage(text, isError) {
els.globalMessage.textContent = text;
els.globalMessage.classList.toggle("req-hidden", !text);
els.globalMessage.classList.toggle("req-error", !!isError);
}
function posterUrl(path, width) {
return path ? `https://image.tmdb.org/t/p/w${width || 342}${path}` : "";
}
function statusName(value) {
if (typeof value === "string") {
return value;
}
return ["Pending", "Approved", "Rejected", "Fulfilled"][value] || "Unknown";
}
function statusClass(value) {
return statusName(value).toLowerCase();
}
function escapeHtml(value) {
return String(value ?? "")
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function setView(view) {
document.querySelectorAll(".req-tab").forEach((tab) => {
tab.classList.toggle("active", tab.dataset.view === view);
});
els.searchView.classList.toggle("req-hidden", view !== "search");
els.mineView.classList.toggle("req-hidden", view !== "mine");
els.adminView.classList.toggle("req-hidden", view !== "admin");
if (view === "mine" || view === "admin") {
loadRequests();
}
}
async function loadStatus() {
try {
state.status = await api("/Status");
if (!state.status.isConfigured) {
els.statusBanner.textContent = "TMDB is not configured. An administrator must set a TMDB API key in Dashboard → Plugins → Request.";
els.statusBanner.classList.remove("req-hidden");
} else if (!state.status.requestSubmissionEnabled) {
els.statusBanner.textContent = "Search is available. Request submission is disabled by the administrator.";
els.statusBanner.classList.remove("req-hidden");
} else {
els.statusBanner.classList.add("req-hidden");
}
} catch (error) {
showMessage(error.message, true);
}
}
async function loadCurrentUser() {
try {
const response = await fetch("/Users/Me", {
cache: "no-store",
headers: authHeader()
});
if (!response.ok) {
return;
}
const me = await response.json();
state.isAdmin = !!me?.Policy?.IsAdministrator;
els.adminTab.classList.toggle("req-hidden", !state.isAdmin);
} catch {
// Non-fatal: admin tab stays hidden.
}
}
async function runSearch() {
const query = els.searchInput.value.trim();
if (!query) {
showMessage("Enter a search query.", true);
return;
}
showMessage("Searching…");
els.detail.classList.add("req-hidden");
try {
const results = await api(`/Search?query=${encodeURIComponent(query)}&type=${encodeURIComponent(state.mediaType)}`);
showMessage(results.length ? "" : "No results found.");
renderResults(results);
} catch (error) {
showMessage(error.message, true);
els.results.innerHTML = "";
}
}
function renderResults(results) {
els.results.innerHTML = results.map((item) => {
const img = item.posterUrl || posterUrl(item.posterPath);
return `
<article class="req-card" data-type="${escapeHtml(item.mediaType)}" data-id="${item.tmdbId}">
${img ? `<img src="${escapeHtml(img)}" alt="" loading="lazy" />` : `<div class="req-card-body"><p class="req-muted">No poster</p></div>`}
<div class="req-card-body">
<p class="req-card-title">${escapeHtml(item.title)}</p>
<p class="req-muted">${escapeHtml(item.mediaType)}${item.year ? ` · ${item.year}` : ""}</p>
</div>
</article>`;
}).join("");
els.results.querySelectorAll(".req-card").forEach((card) => {
card.addEventListener("click", () => openDetail(card.dataset.type, Number(card.dataset.id)));
});
}
async function openDetail(type, tmdbId) {
showMessage("Loading details…");
try {
const detail = await api(`/Media/${encodeURIComponent(type)}/${tmdbId}`);
state.detail = detail;
showMessage("");
renderDetail(detail);
} catch (error) {
showMessage(error.message, true);
}
}
function renderDetail(detail) {
const img = detail.posterUrl || posterUrl(detail.posterPath, 500);
const allowSeasons = state.status?.allowSeasonSelection !== false && detail.mediaType === "tv";
const seasonHtml = allowSeasons
? `<div class="req-seasons">
<label class="req-season"><input type="checkbox" id="allSeasons" checked /> All seasons</label>
${detail.seasons.map((season) => `
<label class="req-season">
<input type="checkbox" class="season-box" value="${season.seasonNumber}" disabled />
${escapeHtml(season.name)} <span class="req-muted">(${season.episodeCount})</span>
</label>`).join("")}
</div>`
: detail.mediaType === "tv"
? `<p class="req-muted">This request will cover all seasons.</p>`
: "";
els.detail.classList.remove("req-hidden");
els.detail.innerHTML = `
${img ? `<img class="req-detail-poster" src="${escapeHtml(img)}" alt="" />` : "<div></div>"}
<div class="req-detail-meta">
<button type="button" class="req-btn" id="backToResults">Back to results</button>
<h2 class="req-detail-title">${escapeHtml(detail.title)}</h2>
<p class="req-muted">${escapeHtml(detail.mediaType)}${detail.year ? ` · ${detail.year}` : ""}</p>
<p>${escapeHtml(detail.overview || "No overview available.")}</p>
${seasonHtml}
<div class="req-detail-actions">
<button type="button" class="req-btn primary" id="submitRequest" ${state.status?.requestSubmissionEnabled ? "" : "disabled"}>
Request
</button>
</div>
</div>`;
els.results.classList.add("req-hidden");
document.getElementById("backToResults").addEventListener("click", () => {
els.detail.classList.add("req-hidden");
els.results.classList.remove("req-hidden");
});
const allSeasons = document.getElementById("allSeasons");
if (allSeasons) {
allSeasons.addEventListener("change", () => {
document.querySelectorAll(".season-box").forEach((box) => {
box.disabled = allSeasons.checked;
if (allSeasons.checked) {
box.checked = false;
}
});
});
}
document.getElementById("submitRequest").addEventListener("click", () => submitRequest(detail));
}
async function submitRequest(detail) {
const payload = {
mediaType: detail.mediaType,
tmdbId: detail.tmdbId,
allSeasons: true,
seasons: null
};
const allSeasons = document.getElementById("allSeasons");
if (detail.mediaType === "tv" && allSeasons && !allSeasons.checked) {
const selected = Array.from(document.querySelectorAll(".season-box:checked")).map((box) => Number(box.value));
if (!selected.length) {
showMessage("Select at least one season, or choose all seasons.", true);
return;
}
payload.allSeasons = false;
payload.seasons = selected;
}
try {
await api("", { method: "POST", body: JSON.stringify(payload) });
showMessage(`Requested “${detail.title}”.`);
} catch (error) {
showMessage(error.message, true);
}
}
async function loadRequests() {
try {
state.requests = await api("");
renderRequestList(els.mineList, state.requests, false);
if (state.isAdmin) {
const pendingFirst = [...state.requests].sort((a, b) => {
const aPending = statusName(a.status) === "Pending" ? 0 : 1;
const bPending = statusName(b.status) === "Pending" ? 0 : 1;
return aPending - bPending || new Date(b.createdAtUtc) - new Date(a.createdAtUtc);
});
renderRequestList(els.adminList, pendingFirst, true);
}
} catch (error) {
showMessage(error.message, true);
}
}
function renderRequestList(container, items, adminMode) {
if (!items.length) {
container.innerHTML = `<p class="req-message">No requests yet.</p>`;
return;
}
container.innerHTML = items.map((item) => {
const img = posterUrl(item.posterPath, 185);
const seasons = item.allSeasons
? "All seasons"
: (item.seasons || []).length
? `Seasons ${(item.seasons || []).join(", ")}`
: "";
const actions = adminMode
? `
<button type="button" class="req-btn" data-action="approve" data-id="${item.id}">Approve</button>
<button type="button" class="req-btn" data-action="reject" data-id="${item.id}">Reject</button>
<button type="button" class="req-btn" data-action="fulfill" data-id="${item.id}">Fulfilled</button>
<button type="button" class="req-btn danger" data-action="delete" data-id="${item.id}">Delete</button>`
: (statusName(item.status) === "Pending"
? `<button type="button" class="req-btn danger" data-action="delete" data-id="${item.id}">Cancel</button>`
: "");
return `
<article class="req-list-item">
${img ? `<img src="${escapeHtml(img)}" alt="" />` : "<div></div>"}
<div>
<p class="req-card-title">${escapeHtml(item.title)}</p>
<p class="req-muted">${escapeHtml(item.mediaType)}${item.year ? ` · ${item.year}` : ""}${seasons ? ` · ${escapeHtml(seasons)}` : ""}</p>
<p class="req-muted">Requested by ${escapeHtml(item.requestedByName)} · ${new Date(item.createdAtUtc).toLocaleString()}</p>
<span class="req-badge ${statusClass(item.status)}">${escapeHtml(statusName(item.status))}</span>
${item.adminNote ? `<p class="req-muted">${escapeHtml(item.adminNote)}</p>` : ""}
</div>
<div class="req-list-actions">${actions}</div>
</article>`;
}).join("");
container.querySelectorAll("[data-action]").forEach((button) => {
button.addEventListener("click", () => handleRequestAction(button.dataset.action, button.dataset.id));
});
}
async function handleRequestAction(action, id) {
try {
if (action === "delete") {
await api(`/${id}`, { method: "DELETE" });
} else {
await api(`/${id}/${action}`, { method: "POST", body: "{}" });
}
await loadRequests();
showMessage("Updated.");
} catch (error) {
showMessage(error.message, true);
}
}
document.querySelectorAll(".req-tab").forEach((tab) => {
tab.addEventListener("click", () => setView(tab.dataset.view));
});
document.querySelectorAll(".req-type-btn").forEach((button) => {
button.addEventListener("click", () => {
document.querySelectorAll(".req-type-btn").forEach((item) => item.classList.remove("active"));
button.classList.add("active");
state.mediaType = button.dataset.type;
});
});
els.searchBtn.addEventListener("click", runSearch);
els.searchInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
runSearch();
}
});
loadStatus();
loadCurrentUser();
})();
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Request</title>
<link rel="stylesheet" href="/Requests/Assets/request.css" />
</head>
<body>
<header class="req-header">
<h1 class="req-title">Request</h1>
<nav class="req-tabs" aria-label="Request views">
<button type="button" class="req-tab active" data-view="search">Search</button>
<button type="button" class="req-tab" data-view="mine">My requests</button>
<button type="button" class="req-tab req-hidden" data-view="admin" id="adminTab">Admin queue</button>
</nav>
</header>
<div id="statusBanner" class="req-status-banner req-hidden"></div>
<p id="globalMessage" class="req-message req-hidden"></p>
<section id="searchView">
<div class="req-search-row">
<input id="searchInput" type="search" placeholder="Search movies or TV shows" autocomplete="off" />
<div class="req-type-toggle" role="group" aria-label="Media type">
<button type="button" class="req-type-btn active" data-type="multi">All</button>
<button type="button" class="req-type-btn" data-type="movie">Movies</button>
<button type="button" class="req-type-btn" data-type="tv">TV</button>
</div>
<button type="button" class="req-btn primary" id="searchBtn">Search</button>
</div>
<div id="results" class="req-grid"></div>
<div id="detail" class="req-detail req-hidden"></div>
</section>
<section id="mineView" class="req-hidden">
<div id="mineList" class="req-list"></div>
</section>
<section id="adminView" class="req-hidden">
<div id="adminList" class="req-list"></div>
</section>
<script src="/Requests/Assets/request.js"></script>
</body>
</html>