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

+
+
+
+ + +
+ Create a free key at themoviedb.org. Stored server-side only; never sent to browsers by plugin APIs. +
+
+ +
+ Leave disabled until TMDB search is configured and tested. +
+ +
+ When unchecked, TV requests always cover all seasons. +
+
+
+ +
+
+
+
+ +
+ + 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("", 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; + } +} diff --git a/Jellyfin.Plugin.Request/Jellyfin.Plugin.Request.csproj b/Jellyfin.Plugin.Request/Jellyfin.Plugin.Request.csproj new file mode 100644 index 0000000..0f67d00 --- /dev/null +++ b/Jellyfin.Plugin.Request/Jellyfin.Plugin.Request.csproj @@ -0,0 +1,33 @@ + + + + net9.0 + Jellyfin.Plugin.Request + Jellyfin.Plugin.Request + true + false + enable + Default + ../jellyfin.ruleset + $(NoWarn);CA1002;CA2227;CA2007;CA1001 + + + + + all + runtime + + + all + runtime + + + + + + + + + + + diff --git a/Jellyfin.Plugin.Request/Plugin.cs b/Jellyfin.Plugin.Request/Plugin.cs new file mode 100644 index 0000000..e3cb0c1 --- /dev/null +++ b/Jellyfin.Plugin.Request/Plugin.cs @@ -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; + +/// +/// Request plugin entry point. +/// +public sealed class Plugin : BasePlugin, IHasWebPages +{ + /// + /// Initializes a new instance of the class. + /// + /// Application paths. + /// XML serializer. + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + } + + /// + public override string Name => "Request"; + + /// + public override string Description => "Local movie and TV request queue with a Request tab in Jellyfin Web."; + + /// + public override Guid Id => Guid.Parse("11c08950-c4bb-484d-89ff-205b3724416b"); + + /// + /// Gets the plugin singleton instance. + /// + public static Plugin? Instance { get; private set; } + + /// + public IEnumerable GetPages() + { + return + [ + new PluginPageInfo + { + Name = Name, + EmbeddedResourcePath = string.Format( + CultureInfo.InvariantCulture, + "{0}.Configuration.configPage.html", + GetType().Namespace) + } + ]; + } +} diff --git a/Jellyfin.Plugin.Request/PluginServiceRegistrator.cs b/Jellyfin.Plugin.Request/PluginServiceRegistrator.cs new file mode 100644 index 0000000..b77ee22 --- /dev/null +++ b/Jellyfin.Plugin.Request/PluginServiceRegistrator.cs @@ -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; + +/// +/// Registers plugin services with the Jellyfin DI container. +/// +public sealed class PluginServiceRegistrator : IPluginServiceRegistrator +{ + /// + public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost) + { + serviceCollection.AddSingleton(); + 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(); + serviceCollection.AddHostedService(); + } +} diff --git a/Jellyfin.Plugin.Request/Storage/MediaRequest.cs b/Jellyfin.Plugin.Request/Storage/MediaRequest.cs new file mode 100644 index 0000000..c0ed793 --- /dev/null +++ b/Jellyfin.Plugin.Request/Storage/MediaRequest.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.Request.Storage; + +/// +/// A user-submitted movie or TV request. +/// +public sealed class MediaRequest +{ + /// + /// Gets or sets the request identifier. + /// + public Guid Id { get; set; } + + /// + /// Gets or sets the media type (movie or tv). + /// + public string MediaType { get; set; } = string.Empty; + + /// + /// Gets or sets the TMDB identifier. + /// + public int TmdbId { get; set; } + + /// + /// Gets or sets the display title. + /// + public string Title { get; set; } = string.Empty; + + /// + /// Gets or sets the release year when known. + /// + public int? Year { get; set; } + + /// + /// Gets or sets the TMDB poster path. + /// + public string? PosterPath { get; set; } + + /// + /// Gets or sets season numbers for TV, or null / empty for all seasons. + /// + public List? Seasons { get; set; } + + /// + /// Gets or sets a value indicating whether all seasons were requested. + /// + public bool AllSeasons { get; set; } + + /// + /// Gets or sets the requesting user's identifier. + /// + public Guid RequestedByUserId { get; set; } + + /// + /// Gets or sets the requesting user's display name. + /// + public string RequestedByName { get; set; } = string.Empty; + + /// + /// Gets or sets the UTC creation timestamp. + /// + public DateTime CreatedAtUtc { get; set; } + + /// + /// Gets or sets the request status. + /// + public RequestStatus Status { get; set; } + + /// + /// Gets or sets an optional administrator note. + /// + public string? AdminNote { get; set; } +} diff --git a/Jellyfin.Plugin.Request/Storage/RequestStatus.cs b/Jellyfin.Plugin.Request/Storage/RequestStatus.cs new file mode 100644 index 0000000..2b29be0 --- /dev/null +++ b/Jellyfin.Plugin.Request/Storage/RequestStatus.cs @@ -0,0 +1,27 @@ +namespace Jellyfin.Plugin.Request.Storage; + +/// +/// Lifecycle status for a media request. +/// +public enum RequestStatus +{ + /// + /// Waiting for administrator review. + /// + Pending = 0, + + /// + /// Approved by an administrator. + /// + Approved = 1, + + /// + /// Rejected by an administrator. + /// + Rejected = 2, + + /// + /// Marked fulfilled by an administrator. + /// + Fulfilled = 3 +} diff --git a/Jellyfin.Plugin.Request/Storage/RequestStore.cs b/Jellyfin.Plugin.Request/Storage/RequestStore.cs new file mode 100644 index 0000000..6eeb039 --- /dev/null +++ b/Jellyfin.Plugin.Request/Storage/RequestStore.cs @@ -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; + +/// +/// Thread-safe JSON persistence for media requests. +/// +public sealed class RequestStore +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly ILogger _logger; + private readonly string _filePath; + private readonly SemaphoreSlim _gate = new(1, 1); + + /// + /// Initializes a new instance of the class. + /// + /// Application paths. + /// Logger. + public RequestStore(IApplicationPaths applicationPaths, ILogger logger) + { + _logger = logger; + var directory = Path.Combine(applicationPaths.PluginConfigurationsPath, "Jellyfin.Plugin.Request"); + Directory.CreateDirectory(directory); + _filePath = Path.Combine(directory, "requests.json"); + } + + /// + /// Loads all requests. + /// + /// Cancellation token. + /// Request list. + public async Task> GetAllAsync(CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await ReadUnlockedAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + /// + /// Adds a request and persists it. + /// + /// Request to add. + /// Cancellation token. + /// The stored request. + public async Task 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(); + } + } + + /// + /// Updates an existing request. + /// + /// Updated request. + /// Cancellation token. + /// True when updated. + public async Task 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(); + } + } + + /// + /// Deletes a request by identifier. + /// + /// Request identifier. + /// Cancellation token. + /// The deleted request, or null. + public async Task 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(); + } + } + + /// + /// Finds a request by identifier. + /// + /// Request identifier. + /// Cancellation token. + /// The request, or null. + public async Task GetByIdAsync(Guid id, CancellationToken cancellationToken) + { + var items = await GetAllAsync(cancellationToken).ConfigureAwait(false); + return items.FirstOrDefault(item => item.Id == id); + } + + private async Task> ReadUnlockedAsync(CancellationToken cancellationToken) + { + if (!File.Exists(_filePath)) + { + return []; + } + + try + { + await using var stream = File.OpenRead(_filePath); + var items = await JsonSerializer.DeserializeAsync>(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 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); + } +} diff --git a/Jellyfin.Plugin.Request/Tmdb/TmdbClient.cs b/Jellyfin.Plugin.Request/Tmdb/TmdbClient.cs new file mode 100644 index 0000000..d03c28f --- /dev/null +++ b/Jellyfin.Plugin.Request/Tmdb/TmdbClient.cs @@ -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; + +/// +/// Server-side TMDB API client. +/// +public sealed class TmdbClient +{ + /// + /// Named HTTP client for TMDB. + /// + public const string HttpClientName = "Tmdb"; + + private readonly IHttpClientFactory _httpClientFactory; + + /// + /// Initializes a new instance of the class. + /// + /// HTTP client factory. + public TmdbClient(IHttpClientFactory httpClientFactory) + { + _httpClientFactory = httpClientFactory; + } + + /// + /// Searches TMDB for movies or TV shows. + /// + /// Search query. + /// movie, tv, or multi. + /// Cancellation token. + /// Search results. + public async Task> 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(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() + .Take(40) + .ToList(); + } + + /// + /// Loads movie or TV details from TMDB. + /// + /// movie or tv. + /// TMDB identifier. + /// Cancellation token. + /// Media detail, or null when not found. + public async Task 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( + $"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( + $"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; + } +} diff --git a/Jellyfin.Plugin.Request/Tmdb/TmdbModels.cs b/Jellyfin.Plugin.Request/Tmdb/TmdbModels.cs new file mode 100644 index 0000000..7a98ff2 --- /dev/null +++ b/Jellyfin.Plugin.Request/Tmdb/TmdbModels.cs @@ -0,0 +1,200 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Jellyfin.Plugin.Request.Tmdb; + +/// +/// Normalized search hit returned to clients. +/// +public sealed class TmdbSearchItem +{ + /// + /// Gets or sets the TMDB identifier. + /// + public int TmdbId { get; set; } + + /// + /// Gets or sets the media type. + /// + public string MediaType { get; set; } = string.Empty; + + /// + /// Gets or sets the title. + /// + public string Title { get; set; } = string.Empty; + + /// + /// Gets or sets the overview. + /// + public string? Overview { get; set; } + + /// + /// Gets or sets the year. + /// + public int? Year { get; set; } + + /// + /// Gets or sets the poster path. + /// + public string? PosterPath { get; set; } + + /// + /// Gets the full poster URL when a path is present. + /// + public string? PosterUrl => string.IsNullOrEmpty(PosterPath) + ? null + : $"https://image.tmdb.org/t/p/w342{PosterPath}"; +} + +/// +/// Normalized media detail returned to clients. +/// +public sealed class TmdbMediaDetail +{ + /// + /// Gets or sets the TMDB identifier. + /// + public int TmdbId { get; set; } + + /// + /// Gets or sets the media type. + /// + public string MediaType { get; set; } = string.Empty; + + /// + /// Gets or sets the title. + /// + public string Title { get; set; } = string.Empty; + + /// + /// Gets or sets the overview. + /// + public string? Overview { get; set; } + + /// + /// Gets or sets the year. + /// + public int? Year { get; set; } + + /// + /// Gets or sets the poster path. + /// + public string? PosterPath { get; set; } + + /// + /// Gets the full poster URL when a path is present. + /// + public string? PosterUrl => string.IsNullOrEmpty(PosterPath) + ? null + : $"https://image.tmdb.org/t/p/w500{PosterPath}"; + + /// + /// Gets or sets TV seasons when applicable. + /// + public List Seasons { get; set; } = []; +} + +/// +/// Season summary for TV detail views. +/// +public sealed class TmdbSeasonInfo +{ + /// + /// Gets or sets the season number. + /// + public int SeasonNumber { get; set; } + + /// + /// Gets or sets the season name. + /// + public string Name { get; set; } = string.Empty; + + /// + /// Gets or sets the episode count. + /// + public int EpisodeCount { get; set; } +} + +internal sealed class TmdbSearchResponse +{ + [JsonPropertyName("results")] + public List 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 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; } +} diff --git a/Jellyfin.Plugin.Request/Web/nav-loader.js b/Jellyfin.Plugin.Request/Web/nav-loader.js new file mode 100644 index 0000000..112a0be --- /dev/null +++ b/Jellyfin.Plugin.Request/Web/nav-loader.js @@ -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 }); +})(); diff --git a/Jellyfin.Plugin.Request/Web/request.css b/Jellyfin.Plugin.Request/Web/request.css new file mode 100644 index 0000000..4d5373f --- /dev/null +++ b/Jellyfin.Plugin.Request/Web/request.css @@ -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; + } +} diff --git a/Jellyfin.Plugin.Request/Web/request.js b/Jellyfin.Plugin.Request/Web/request.js new file mode 100644 index 0000000..e36d6f3 --- /dev/null +++ b/Jellyfin.Plugin.Request/Web/request.js @@ -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("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); + } + + 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 ` +
+ ${img ? `` : `

No poster

`} +
+

${escapeHtml(item.title)}

+

${escapeHtml(item.mediaType)}${item.year ? ` · ${item.year}` : ""}

+
+
`; + }).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 + ? `
+ + ${detail.seasons.map((season) => ` + `).join("")} +
` + : detail.mediaType === "tv" + ? `

This request will cover all seasons.

` + : ""; + + els.detail.classList.remove("req-hidden"); + els.detail.innerHTML = ` + ${img ? `` : "
"} +
+ +

${escapeHtml(detail.title)}

+

${escapeHtml(detail.mediaType)}${detail.year ? ` · ${detail.year}` : ""}

+

${escapeHtml(detail.overview || "No overview available.")}

+ ${seasonHtml} +
+ +
+
`; + + 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 = `

No requests yet.

`; + 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 + ? ` + + + + ` + : (statusName(item.status) === "Pending" + ? `` + : ""); + + return ` +
+ ${img ? `` : "
"} +
+

${escapeHtml(item.title)}

+

${escapeHtml(item.mediaType)}${item.year ? ` · ${item.year}` : ""}${seasons ? ` · ${escapeHtml(seasons)}` : ""}

+

Requested by ${escapeHtml(item.requestedByName)} · ${new Date(item.createdAtUtc).toLocaleString()}

+ ${escapeHtml(statusName(item.status))} + ${item.adminNote ? `

${escapeHtml(item.adminNote)}

` : ""} +
+
${actions}
+
`; + }).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(); +})(); diff --git a/Jellyfin.Plugin.Request/Web/requestPage.html b/Jellyfin.Plugin.Request/Web/requestPage.html new file mode 100644 index 0000000..dce9121 --- /dev/null +++ b/Jellyfin.Plugin.Request/Web/requestPage.html @@ -0,0 +1,46 @@ + + + + + + Request + + + +
+

Request

+ +
+ +
+

+ +
+
+ +
+ + + +
+ +
+
+
+
+ +
+
+
+ +
+
+
+ + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..cada4a0 --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +# Jellyfin Request Plugin + +Local movie and TV request queue for Jellyfin. Users search TMDB from a **Request** tab, submit titles into a JSON-backed queue, and administrators approve, reject, or mark them fulfilled. + +No Jellyseerr, Radarr, or Sonarr integration in v1 — this is an admin review queue only. + +## Install from repository (recommended) + +Jellyfin does not clone git repos for plugins. It reads a `manifest.json` URL and downloads the zip listed there (same pattern as SeerrFin). + +1. In Jellyfin open **Dashboard → Plugins → Repositories → +** +2. Add: + - **Name:** `Request` + - **URL:** + +```text +https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main/manifest.json +``` + +3. Open **Catalog**, find **Request**, install it, then restart Jellyfin. +4. Configure under **Dashboard → Plugins → Request** (TMDB API key + enable submissions). + +## Requirements + +- Jellyfin Server **10.11.x** +- .NET SDK **9+** to build from source +- A free [TMDB API key](https://www.themoviedb.org/settings/api) + +## Build / package a release + +```powershell +dotnet restore Jellyfin.Plugin.Request.sln +.\scripts\package-release.ps1 +``` + +That rebuilds the DLL, writes `release/Jellyfin.Plugin.Request_10.11.0.zip`, and refreshes `manifest.json` (including the MD5 checksum Jellyfin verifies). + +Commit and push `manifest.json` + `release/*.zip` so the raw Gitea URLs stay valid. + +Manual DLL path (sideload only): + +```text +Jellyfin.Plugin.Request\bin\Release\net9.0\Jellyfin.Plugin.Request.dll +``` + +## Request nav tab + +On startup the plugin tries to inject: + +```html + +``` + +into jellyfin-web `index.html`. That adds a **Request** item to the top library tabs and side menu. + +Docker and some packaged installs make `index.html` read-only. If the tab does not appear, run the matching script with a writable path: + +```bash +sudo bash scripts/install-web-loader.sh /usr/share/jellyfin/web/index.html +``` + +```powershell +.\scripts\install-web-loader.ps1 -IndexPath "C:\Program Files\Jellyfin\Server\jellyfin-web\index.html" +``` + +Jellyfin updates can replace `index.html`. Re-run the install script if the tab disappears. + +Uninstall helpers: + +- `scripts/uninstall-web-loader.sh` +- `scripts/uninstall-web-loader.ps1` + +## API overview + +Authenticated Jellyfin users call plugin endpoints under `/Requests`: + +| Method | Path | Notes | +|--------|------|-------| +| GET | `/Requests/Status` | Non-secret status | +| GET | `/Requests/Page` | Request UI | +| GET | `/Requests/Search` | TMDB search | +| GET | `/Requests/Media/{type}/{tmdbId}` | Movie/TV detail | +| GET | `/Requests` | List (own requests; admins see all) | +| POST | `/Requests` | Create request | +| POST | `/Requests/{id}/approve` | Admin | +| POST | `/Requests/{id}/reject` | Admin | +| POST | `/Requests/{id}/fulfill` | Admin | +| DELETE | `/Requests/{id}` | Admin, or owner while Pending | + +The TMDB API key stays on the server. Browsers never receive it. + +## Data storage + +Requests are stored at: + +```text +{PluginConfigurationsPath}/Jellyfin.Plugin.Request/requests.json +``` + +## License + +GPLv3 (same constraint as other Jellyfin plugins that link against Jellyfin packages). diff --git a/build.yaml b/build.yaml new file mode 100644 index 0000000..7206231 --- /dev/null +++ b/build.yaml @@ -0,0 +1,16 @@ +--- +name: "Request" +guid: "11c08950-c4bb-484d-89ff-205b3724416b" +version: "1.0.0.0" +targetAbi: "10.11.0.0" +framework: "net9.0" +overview: "Request movies and TV shows from a local admin review queue" +description: > + Adds a Request tab to Jellyfin Web so users can search TMDB and submit + movie and TV requests into a local queue for administrators to review. +category: "General" +owner: "Michael-A-Sloan" +artifacts: + - "Jellyfin.Plugin.Request.dll" +changelog: > + Initial release: local request queue, TMDB search, Request nav tab diff --git a/jellyfin.ruleset b/jellyfin.ruleset new file mode 100644 index 0000000..8af791c --- /dev/null +++ b/jellyfin.ruleset @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..b78ca97 --- /dev/null +++ b/manifest.json @@ -0,0 +1,22 @@ +[ + { + "guid": "11c08950-c4bb-484d-89ff-205b3724416b", + "name": "Request", + "description": "Adds a Request tab to Jellyfin Web so users can search TMDB and submit movie and TV requests into a local queue for administrators to review.", + "overview": "Request movies and TV shows from a local admin review queue", + "owner": "Michael-A-Sloan", + "category": "General", + "repositoryUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies", + "versions": [ + { + "version": "1.0.0.0", + "changelog": "Initial release: local request queue, TMDB search, Request nav tab", + "targetAbi": "10.11.0.0", + "sourceUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main/release/Jellyfin.Plugin.Request_10.11.0.zip", + "checksum": "E23CF5FF9E0F58BEDE6FC3A2BFF9FE6D", + "timestamp": "2026-08-02T20:29:32.0000000Z", + "dependencies": [] + } + ] + } +] diff --git a/release/Jellyfin.Plugin.Request_10.11.0.zip b/release/Jellyfin.Plugin.Request_10.11.0.zip new file mode 100644 index 0000000..02c086a Binary files /dev/null and b/release/Jellyfin.Plugin.Request_10.11.0.zip differ diff --git a/scripts/install-web-loader.ps1 b/scripts/install-web-loader.ps1 new file mode 100644 index 0000000..805e569 --- /dev/null +++ b/scripts/install-web-loader.ps1 @@ -0,0 +1,53 @@ +param( + [string]$IndexPath = "" +) + +$ErrorActionPreference = "Stop" + +$loaderSrc = "/Requests/Assets/nav-loader.js" +$markerStart = "" +$markerEnd = "" + +if (-not $IndexPath) { + $candidates = @( + (Join-Path $env:LOCALAPPDATA "jellyfin\jellyfin-web\index.html"), + "C:\Program Files\Jellyfin\Server\jellyfin-web\index.html", + "C:\ProgramData\Jellyfin\Server\jellyfin-web\index.html" + ) + foreach ($candidate in $candidates) { + if (Test-Path $candidate) { + $IndexPath = $candidate + break + } + } +} + +if (-not $IndexPath -or -not (Test-Path $IndexPath)) { + Write-Error "Could not find jellyfin-web index.html. Pass -IndexPath explicitly." +} + +$html = Get-Content -Raw -Path $IndexPath +if ($html -like "*$loaderSrc*") { + Write-Host "Request web loader is already installed in $IndexPath" + exit 0 +} + +$backupPath = "$IndexPath.bak.request.$(Get-Date -Format 'yyyyMMddHHmmss')" +Copy-Item -Path $IndexPath -Destination $backupPath + +$block = @" +$markerStart + +$markerEnd +"@ + +if ($html -match '(?i)') { + $updated = [regex]::Replace($html, '(?i)', ($block + "`r`n"), 1) +} else { + $updated = $html + "`r`n" + $block + "`r`n" +} + +Set-Content -Path $IndexPath -Value $updated -NoNewline +Write-Host "Installed Request web loader in $IndexPath" +Write-Host "Backup saved to $backupPath" +Write-Host "Restart Jellyfin, then hard refresh the browser." diff --git a/scripts/install-web-loader.sh b/scripts/install-web-loader.sh new file mode 100644 index 0000000..378b17d --- /dev/null +++ b/scripts/install-web-loader.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +set -euo pipefail + +loader_src="/Requests/Assets/nav-loader.js" +marker_start="" +marker_end="" + +usage() { + cat <&2 + usage + echo "Pass the path explicitly, for example:" >&2 + echo " sudo bash scripts/install-web-loader.sh /usr/share/jellyfin/web/index.html" >&2 + exit 1 +fi + +if [ ! -w "$index_path" ]; then + echo "Cannot write to $index_path. Run this script with sudo or fix permissions." >&2 + exit 1 +fi + +if grep -Fq "$loader_src" "$index_path"; then + echo "Request web loader is already installed in $index_path" + exit 0 +fi + +backup_path="${index_path}.bak.request.$(date -u +%Y%m%d%H%M%S)" +cp -p "$index_path" "$backup_path" + +tmp_path="$(mktemp)" +block="${marker_start} + +${marker_end}" + +awk -v block="$block" ' + BEGIN { inserted = 0 } + /<\/body>/ && inserted == 0 { + print block + inserted = 1 + } + { print } + END { + if (inserted == 0) { + print block + } + } +' "$index_path" > "$tmp_path" + +cat "$tmp_path" > "$index_path" +rm -f "$tmp_path" + +echo "Installed Request web loader in $index_path" +echo "Backup saved to $backup_path" +echo "Restart Jellyfin, then hard refresh the browser." diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1 new file mode 100644 index 0000000..192db6a --- /dev/null +++ b/scripts/package-release.ps1 @@ -0,0 +1,93 @@ +param( + [string]$Version = "1.0.0.0", + [string]$TargetAbi = "10.11.0.0", + [string]$RepoRawBase = "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main" +) + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root + +$guid = "11c08950-c4bb-484d-89ff-205b3724416b" +$pluginName = "Request" +$zipFileName = "Jellyfin.Plugin.Request_10.11.0.zip" +$releaseDir = Join-Path $root "release" +$stageDir = Join-Path $releaseDir "stage" +$dllPath = Join-Path $root "Jellyfin.Plugin.Request\bin\Release\net9.0\Jellyfin.Plugin.Request.dll" +$zipPath = Join-Path $releaseDir $zipFileName +$manifestPath = Join-Path $root "manifest.json" +$timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") +$changelog = "Initial release: local request queue, TMDB search, Request nav tab" + +Write-Host "Building plugin..." +dotnet build (Join-Path $root "Jellyfin.Plugin.Request.sln") -c Release +if (-not (Test-Path $dllPath)) { + throw "DLL not found at $dllPath" +} + +New-Item -ItemType Directory -Force -Path $releaseDir | Out-Null +if (Test-Path $stageDir) { + Remove-Item $stageDir -Recurse -Force +} +New-Item -ItemType Directory -Force -Path $stageDir | Out-Null + +$meta = [ordered]@{ + guid = $guid + name = $pluginName + description = "Adds a Request tab to Jellyfin Web so users can search TMDB and submit movie and TV requests into a local queue for administrators to review." + overview = "Request movies and TV shows from a local admin review queue" + owner = "Michael-A-Sloan" + category = "General" + version = $Version + changelog = $changelog + targetAbi = $TargetAbi + framework = "net9.0" + timestamp = $timestamp +} +$metaJson = $meta | ConvertTo-Json -Depth 5 +[System.IO.File]::WriteAllText((Join-Path $stageDir "meta.json"), $metaJson) +Copy-Item $dllPath -Destination (Join-Path $stageDir "Jellyfin.Plugin.Request.dll") + +$tempZip = Join-Path $releaseDir ("tmp_" + [guid]::NewGuid().ToString("N") + ".zip") +Compress-Archive -Path (Join-Path $stageDir "*") -DestinationPath $tempZip -Force +Remove-Item $stageDir -Recurse -Force + +if (Test-Path $zipPath) { + Remove-Item $zipPath -Force -ErrorAction SilentlyContinue + Start-Sleep -Milliseconds 200 +} +Move-Item -Path $tempZip -Destination $zipPath -Force + +$checksum = (Get-FileHash -Path $zipPath -Algorithm MD5).Hash.ToUpperInvariant() +$sourceUrl = "$RepoRawBase/release/$zipFileName" + +$versionObj = [ordered]@{ + version = $Version + changelog = $changelog + targetAbi = $TargetAbi + sourceUrl = $sourceUrl + checksum = $checksum + timestamp = $timestamp + dependencies = @() +} +$plugin = [ordered]@{ + guid = $guid + name = $pluginName + description = "Adds a Request tab to Jellyfin Web so users can search TMDB and submit movie and TV requests into a local queue for administrators to review." + overview = "Request movies and TV shows from a local admin review queue" + owner = "Michael-A-Sloan" + category = "General" + repositoryUrl = "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies" + versions = @($versionObj) +} + +# Jellyfin requires a JSON array root. +$pluginJson = ($plugin | ConvertTo-Json -Depth 8) +$manifestJson = "[" + [Environment]::NewLine + $pluginJson + [Environment]::NewLine + "]" +[System.IO.File]::WriteAllText($manifestPath, $manifestJson) + +Write-Host "Packaged: $zipPath" +Write-Host "Checksum: $checksum" +Write-Host "Manifest: $manifestPath" +Write-Host "Jellyfin repository URL:" +Write-Host " $RepoRawBase/manifest.json" diff --git a/scripts/uninstall-web-loader.ps1 b/scripts/uninstall-web-loader.ps1 new file mode 100644 index 0000000..a3ad740 --- /dev/null +++ b/scripts/uninstall-web-loader.ps1 @@ -0,0 +1,44 @@ +param( + [string]$IndexPath = "" +) + +$ErrorActionPreference = "Stop" + +$loaderSrc = "/Requests/Assets/nav-loader.js" +$markerStart = "" +$markerEnd = "" + +if (-not $IndexPath) { + $candidates = @( + (Join-Path $env:LOCALAPPDATA "jellyfin\jellyfin-web\index.html"), + "C:\Program Files\Jellyfin\Server\jellyfin-web\index.html", + "C:\ProgramData\Jellyfin\Server\jellyfin-web\index.html" + ) + foreach ($candidate in $candidates) { + if (Test-Path $candidate) { + $IndexPath = $candidate + break + } + } +} + +if (-not $IndexPath -or -not (Test-Path $IndexPath)) { + Write-Error "Could not find jellyfin-web index.html. Pass -IndexPath explicitly." +} + +$html = Get-Content -Raw -Path $IndexPath +if (($html -notlike "*$loaderSrc*") -and ($html -notlike "*$markerStart*")) { + Write-Host "Request web loader is not installed in $IndexPath" + exit 0 +} + +$backupPath = "$IndexPath.bak.request.uninstall.$(Get-Date -Format 'yyyyMMddHHmmss')" +Copy-Item -Path $IndexPath -Destination $backupPath + +$pattern = "(?s)\s*$([regex]::Escape($markerStart)).*?$([regex]::Escape($markerEnd))\s*" +$updated = [regex]::Replace($html, $pattern, "`r`n") +$updated = [regex]::Replace($updated, "(?im)^\s*]*nav-loader\.js[^>]*>\s*\s*`r?`n?", "") + +Set-Content -Path $IndexPath -Value $updated -NoNewline +Write-Host "Removed Request web loader from $IndexPath" +Write-Host "Backup saved to $backupPath" diff --git a/scripts/uninstall-web-loader.sh b/scripts/uninstall-web-loader.sh new file mode 100644 index 0000000..0407991 --- /dev/null +++ b/scripts/uninstall-web-loader.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +set -euo pipefail + +loader_src="/Requests/Assets/nav-loader.js" +marker_start="" +marker_end="" + +index_path="${1:-}" +if [ -z "$index_path" ]; then + for candidate in \ + /usr/share/jellyfin/web/index.html \ + /usr/lib/jellyfin/bin/jellyfin-web/index.html \ + /config/jellyfin-web/index.html + do + if [ -f "$candidate" ]; then + index_path="$candidate" + break + fi + done +fi + +if [ -z "$index_path" ] || [ ! -f "$index_path" ]; then + echo "Could not find jellyfin-web index.html." >&2 + exit 1 +fi + +if [ ! -w "$index_path" ]; then + echo "Cannot write to $index_path. Run this script with sudo or fix permissions." >&2 + exit 1 +fi + +if ! grep -Fq "$loader_src" "$index_path" && ! grep -Fq "$marker_start" "$index_path"; then + echo "Request web loader is not installed in $index_path" + exit 0 +fi + +backup_path="${index_path}.bak.request.uninstall.$(date -u +%Y%m%d%H%M%S)" +cp -p "$index_path" "$backup_path" + +tmp_path="$(mktemp)" +awk -v start="$marker_start" -v end="$marker_end" -v src="$loader_src" ' + $0 ~ start { skip = 1; next } + skip && $0 ~ end { skip = 0; next } + skip { next } + index($0, src) { next } + { print } +' "$index_path" > "$tmp_path" + +cat "$tmp_path" > "$index_path" +rm -f "$tmp_path" + +echo "Removed Request web loader from $index_path" +echo "Backup saved to $backup_path"