Compare commits

..
10 Commits
Author SHA1 Message Date
Michael SloanandCursor db166bfc02 fix(nav): reduce request tab flicker on home return
Hide the Request tab instead of removing it off-home, cache the button/panel, and reinject immediately when Jellyfin rebuilds the home tab bar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 21:38:28 -04:00
Michael SloanandCursor 7044023d98 feat(request): custom titles and remount blank request tab
Allow movie/TV requests without a TMDB match via a Custom form, and remount the embedded Request UI when the home tab opens empty.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:46:53 -04:00
Michael SloanandCursor 2eed62390b fix(admin): gate queue actions and harden approve flow
Expose isAdmin from Status, show Admin queue controls only for administrators, and return clear 403/404 messages for approve/reject/fulfill/delete.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:40:27 -04:00
Michael SloanandCursor 3957c6ac1d fix(ui): normalize request list fields for jellyfin json
Accept PascalCase or camelCase properties so My requests and Admin queue show title, requester, date, and status correctly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:38:10 -04:00
Michael SloanandCursor 97619f1eb5 fix(api): harden request submit path and errors
Use ApiClient server address for API calls, return 201 without CreatedAtAction route issues, and surface clearer validation messages when submit fails.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:32:22 -04:00
Michael SloanandCursor bfa8115fd0 fix(nav): inject request tab via FT HTTP endpoint
File Transformation reflection callbacks often fail across plugin load contexts; register an anonymous TransformIndexHtml endpoint as the reliable injection path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:25:31 -04:00
Michael SloanandCursor e260677dab feat(tmdb): show search results with dual auth
Accept TMDB v3 API key or Read Access Token (Bearer), surface TMDB error messages, and display query/result count in the Request UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:05:32 -04:00
Michael SloanandCursor 2a1fcf0588 fix(nav): show request panel on home tab select
Jellyfin HomeView only handles Home/Favorites; stop its tabchange handler for Request and sync .hide/is-active so the embedded UI is visible.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:03:57 -04:00
Michael SloanandCursor 0a5ea07838 feat(nav): embed request ui in home top tabs
Replace full-page navigation with a native emby-tab-button and pageTabContent panel so Request behaves like Home and Favorites.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 17:00:07 -04:00
Michael SloanandCursor eb20e64c37 chore(release): stop tracking temporary package zip files
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 16:48:22 -04:00
28 changed files with 1324 additions and 405 deletions

No files matched your search

+3
View File
@@ -49,3 +49,6 @@ artifacts/
release/stage/
release/tmp_*.zip
+3 -3
View File
@@ -1,7 +1,7 @@
<Project>
<PropertyGroup>
<Version>1.0.0.2</Version>
<AssemblyVersion>1.0.0.2</AssemblyVersion>
<FileVersion>1.0.0.2</FileVersion>
<Version>1.0.1.1</Version>
<AssemblyVersion>1.0.1.1</AssemblyVersion>
<FileVersion>1.0.1.1</FileVersion>
</PropertyGroup>
</Project>
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Jellyfin.Plugin.Request.Api;
@@ -11,15 +10,33 @@ 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.
/// Gets or sets the TMDB identifier. Ignored for custom requests.
/// </summary>
[Range(1, int.MaxValue)]
public int TmdbId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this is a custom title not on TMDB.
/// </summary>
public bool IsCustom { get; set; }
/// <summary>
/// Gets or sets the title for custom requests.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets an optional release year for custom requests.
/// </summary>
public int? Year { get; set; }
/// <summary>
/// Gets or sets optional requester notes.
/// </summary>
public string? Notes { get; set; }
/// <summary>
/// Gets or sets optional season numbers for TV.
/// Null or empty with <see cref="AllSeasons"/> true requests everything.
+141 -17
View File
@@ -9,6 +9,7 @@ using System.Threading.Tasks;
using Jellyfin.Data;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Plugin.Request.Configuration;
using Jellyfin.Plugin.Request.Hosting;
using Jellyfin.Plugin.Request.Storage;
using Jellyfin.Plugin.Request.Tmdb;
using MediaBrowser.Controller.Library;
@@ -60,11 +61,14 @@ public sealed class RequestController : ControllerBase
public ActionResult<object> Status()
{
var config = GetConfig();
var userId = GetUserId();
return Ok(new
{
isConfigured = !string.IsNullOrWhiteSpace(config.TmdbApiKey),
requestSubmissionEnabled = config.EnableRequestSubmission,
allowSeasonSelection = config.AllowSeasonSelection
allowSeasonSelection = config.AllowSeasonSelection,
isAuthenticated = userId != Guid.Empty,
isAdmin = userId != Guid.Empty && IsAdministrator(userId)
});
}
@@ -79,6 +83,20 @@ public sealed class RequestController : ControllerBase
return EmbeddedFile("Web.requestPage.html", "text/html; charset=utf-8");
}
/// <summary>
/// File Transformation endpoint: injects nav-loader.js into jellyfin-web index.html.
/// Must stay anonymous because File Transformation calls it without auth.
/// </summary>
/// <param name="payload">Current file contents.</param>
/// <returns>Transformed HTML body.</returns>
[HttpPost("TransformIndexHtml")]
[AllowAnonymous]
public ContentResult TransformIndexHtml([FromBody] IndexHtmlPatchPayload payload)
{
var html = WebNavInjector.InjectHtml(payload?.Contents ?? string.Empty);
return Content(html, "text/html; charset=utf-8");
}
/// <summary>
/// Serves plugin web assets.
/// </summary>
@@ -203,25 +221,83 @@ public sealed class RequestController : ControllerBase
/// <returns>Created request.</returns>
[HttpPost]
public async Task<ActionResult<MediaRequest>> Create(
[FromBody] CreateRequestDto body,
[FromBody] CreateRequestDto? body,
CancellationToken cancellationToken)
{
var config = GetConfig();
if (!config.EnableRequestSubmission)
{
return StatusCode(StatusCodes.Status403Forbidden, new { message = "Request submission is disabled." });
return StatusCode(StatusCodes.Status403Forbidden, new { message = "Request submission is disabled. Enable it in Dashboard → Plugins → Request." });
}
var userId = GetUserId();
if (userId == Guid.Empty)
{
return Unauthorized();
return Unauthorized(new { message = "You must be signed in to submit a request." });
}
if (body is null)
{
return BadRequest(new { message = "Request body is required." });
}
var mediaType = NormalizeMediaType(body.MediaType);
if (mediaType is null || body.TmdbId <= 0)
if (mediaType is null)
{
return BadRequest(new { message = "mediaType must be movie or tv and tmdbId must be positive." });
return BadRequest(new { message = "mediaType must be movie or tv." });
}
if (body.IsCustom)
{
var customTitle = (body.Title ?? string.Empty).Trim();
if (customTitle.Length is < 1 or > 200)
{
return BadRequest(new { message = "Custom requests need a title (1–200 characters)." });
}
if (body.Year.HasValue && (body.Year.Value < 1870 || body.Year.Value > 2100))
{
return BadRequest(new { message = "Year must be between 1870 and 2100 when provided." });
}
var notes = string.IsNullOrWhiteSpace(body.Notes) ? null : body.Notes.Trim();
if (notes is { Length: > 1000 })
{
return BadRequest(new { message = "Notes must be 1000 characters or fewer." });
}
var existingCustom = await _store.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (HasCustomDuplicate(existingCustom, userId, mediaType, customTitle, body.Year))
{
return Conflict(new { message = "You already have an open request for this custom title." });
}
var customUser = _userManager.GetUserById(userId);
var customRequest = new MediaRequest
{
Id = Guid.NewGuid(),
MediaType = mediaType,
TmdbId = 0,
IsCustom = true,
Title = customTitle,
Year = body.Year,
Notes = notes,
PosterPath = null,
Seasons = null,
AllSeasons = mediaType == "tv",
RequestedByUserId = userId,
RequestedByName = customUser?.Username ?? "Unknown",
CreatedAtUtc = DateTime.UtcNow,
Status = RequestStatus.Pending
};
await _store.AddAsync(customRequest, cancellationToken).ConfigureAwait(false);
return StatusCode(StatusCodes.Status201Created, customRequest);
}
if (body.TmdbId <= 0)
{
return BadRequest(new { message = "tmdbId must be positive for TMDB requests." });
}
var allSeasons = body.AllSeasons;
@@ -267,8 +343,10 @@ public sealed class RequestController : ControllerBase
Id = Guid.NewGuid(),
MediaType = mediaType,
TmdbId = detail.TmdbId,
IsCustom = false,
Title = detail.Title,
Year = detail.Year,
Notes = string.IsNullOrWhiteSpace(body.Notes) ? null : body.Notes.Trim(),
PosterPath = detail.PosterPath,
Seasons = seasons,
AllSeasons = mediaType == "tv" && allSeasons,
@@ -279,7 +357,7 @@ public sealed class RequestController : ControllerBase
};
await _store.AddAsync(request, cancellationToken).ConfigureAwait(false);
return CreatedAtAction(nameof(List), new { id = request.Id }, request);
return StatusCode(StatusCodes.Status201Created, request);
}
/// <summary>
@@ -342,19 +420,19 @@ public sealed class RequestController : ControllerBase
var userId = GetUserId();
if (userId == Guid.Empty)
{
return Unauthorized();
return Unauthorized(new { message = "You must be signed in." });
}
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
if (existing is null)
{
return NotFound();
return NotFound(new { message = "Request not found." });
}
var isAdmin = IsAdministrator(userId);
if (!isAdmin && (existing.RequestedByUserId != userId || existing.Status != RequestStatus.Pending))
{
return Forbid();
return StatusCode(StatusCodes.Status403Forbidden, new { message = "You can only cancel your own pending requests." });
}
await _store.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
@@ -370,18 +448,18 @@ public sealed class RequestController : ControllerBase
var userId = GetUserId();
if (userId == Guid.Empty)
{
return Unauthorized();
return Unauthorized(new { message = "You must be signed in." });
}
if (!IsAdministrator(userId))
{
return Forbid();
return StatusCode(StatusCodes.Status403Forbidden, new { message = "Administrator access is required." });
}
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
if (existing is null)
{
return NotFound();
return NotFound(new { message = "Request not found." });
}
existing.Status = status;
@@ -405,6 +483,7 @@ public sealed class RequestController : ControllerBase
foreach (var item in existing)
{
if (item.RequestedByUserId != userId
|| item.IsCustom
|| !item.MediaType.Equals(mediaType, StringComparison.OrdinalIgnoreCase)
|| item.TmdbId != tmdbId
|| item.Status is not (RequestStatus.Pending or RequestStatus.Approved))
@@ -436,6 +515,35 @@ public sealed class RequestController : ControllerBase
return false;
}
private static bool HasCustomDuplicate(
IReadOnlyList<MediaRequest> existing,
Guid userId,
string mediaType,
string title,
int? year)
{
foreach (var item in existing)
{
if (item.RequestedByUserId != userId
|| !item.IsCustom
|| !item.MediaType.Equals(mediaType, StringComparison.OrdinalIgnoreCase)
|| item.Status is not (RequestStatus.Pending or RequestStatus.Approved)
|| !item.Title.Equals(title, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (year.HasValue && item.Year.HasValue && year.Value != item.Year.Value)
{
continue;
}
return true;
}
return false;
}
private static PluginConfiguration GetConfig()
{
return Plugin.Instance?.Configuration ?? new PluginConfiguration();
@@ -443,10 +551,26 @@ public sealed class RequestController : ControllerBase
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;
string?[] candidates =
[
User.FindFirstValue(ClaimTypes.NameIdentifier),
User.FindFirstValue("sub"),
User.FindFirstValue("Jellyfin-UserId"),
User.FindFirstValue("http://jellyfin.media/claims/user-id"),
User.Claims.FirstOrDefault(claim =>
claim.Type.EndsWith("/nameidentifier", StringComparison.OrdinalIgnoreCase)
|| claim.Type.Equals("userid", StringComparison.OrdinalIgnoreCase))?.Value
];
foreach (var raw in candidates)
{
if (Guid.TryParse(raw, out var userId) && userId != Guid.Empty)
{
return userId;
}
}
return Guid.Empty;
}
private bool IsAdministrator(Guid userId)
@@ -13,10 +13,12 @@
</div>
<div class="verticalSection">
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="TmdbApiKey">TMDB API key</label>
<label class="inputLabel inputLabelUnfocused" for="TmdbApiKey">TMDB API key or Read Access Token</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.
From <a is="emby-linkbutton" class="button-link" href="https://www.themoviedb.org/settings/api" target="_blank" rel="noopener">TMDB API settings</a>:
paste either the v3 API Key or the API Read Access Token (Bearer).
Stored server-side only. Docs: <a is="emby-linkbutton" class="button-link" href="https://developer.themoviedb.org/docs/getting-started" target="_blank" rel="noopener">Getting Started</a>.
</div>
</div>
<label class="checkboxContainer">
@@ -1,12 +1,17 @@
using System.Text.Json.Serialization;
using Newtonsoft.Json;
namespace Jellyfin.Plugin.Request.Hosting;
/// <summary>
/// Payload shape expected by the File Transformation callback.
/// Payload shape expected by the File Transformation callback/endpoint.
/// </summary>
public sealed class IndexHtmlPatchPayload
{
/// <summary>
/// Gets or sets the current file contents.
/// </summary>
[JsonProperty("contents")]
[JsonPropertyName("contents")]
public string Contents { get; set; } = string.Empty;
}
@@ -18,9 +18,14 @@ namespace Jellyfin.Plugin.Request.Hosting;
/// </summary>
public sealed class WebNavInjector : IHostedService
{
private const string LoaderSrc = "/Requests/Assets/nav-loader.js";
/// <summary>
/// Script URL injected into jellyfin-web index.html.
/// </summary>
public const string LoaderSrc = "/Requests/Assets/nav-loader.js?v=1.0.1.1";
private const string MarkerStart = "<!-- jellyfin-plugin-request-nav-start -->";
private const string MarkerEnd = "<!-- jellyfin-plugin-request-nav-end -->";
private const string TransformationEndpoint = "/Requests/TransformIndexHtml";
private static readonly Guid TransformationId = Guid.Parse("11c08950-c4bb-484d-89ff-205b3724416b");
private readonly IServerApplicationPaths _applicationPaths;
@@ -43,12 +48,14 @@ public sealed class WebNavInjector : IHostedService
{
if (TryRegisterFileTransformation())
{
_logger.LogInformation("Request nav loader registered with File Transformation for index.html.");
_logger.LogInformation(
"Request nav loader registered with File Transformation (callback + {Endpoint}).",
TransformationEndpoint);
return Task.CompletedTask;
}
_logger.LogWarning(
"File Transformation plugin was not found. Install it from https://www.iamparadox.dev/jellyfin/plugins/manifest.json for reliable Request tab injection. Falling back to disk patch.");
"File Transformation plugin was not found yet. Install/enable it from https://www.iamparadox.dev/jellyfin/plugins/manifest.json. Falling back to disk patch and retrying registration.");
try
{
@@ -73,14 +80,25 @@ public sealed class WebNavInjector : IHostedService
}
/// <summary>
/// File Transformation callback: injects the nav-loader script tag into index.html contents.
/// File Transformation reflection callback.
/// </summary>
/// <param name="payload">Current file contents.</param>
/// <param name="payload">Current file contents wrapper.</param>
/// <returns>Transformed HTML.</returns>
public static string InjectNavLoader(IndexHtmlPatchPayload payload)
public static string InjectNavLoader(JObject payload)
{
var html = payload?.Contents ?? string.Empty;
if (html.Contains(LoaderSrc, StringComparison.Ordinal)
var html = payload?["contents"]?.ToString() ?? string.Empty;
return InjectHtml(html);
}
/// <summary>
/// Injects the nav-loader script tag into index.html contents.
/// </summary>
/// <param name="html">Current HTML.</param>
/// <returns>Transformed HTML.</returns>
public static string InjectHtml(string html)
{
html ??= string.Empty;
if (html.Contains("/Requests/Assets/nav-loader.js", StringComparison.Ordinal)
|| html.Contains(MarkerStart, StringComparison.Ordinal))
{
return html;
@@ -95,11 +113,12 @@ public sealed class WebNavInjector : IHostedService
private async Task RetryRegisterAsync(CancellationToken cancellationToken)
{
for (var attempt = 1; attempt <= 10; attempt++)
for (var attempt = 1; attempt <= 12; attempt++)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3 * attempt), cancellationToken).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(Math.Min(3 * attempt, 20)), cancellationToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -116,7 +135,7 @@ public sealed class WebNavInjector : IHostedService
}
_logger.LogWarning(
"File Transformation still unavailable after retries. Use scripts/install-web-loader.sh|.ps1 if the Request tab is missing.");
"File Transformation still unavailable after retries. Request tab will not appear until File Transformation is installed and Jellyfin is restarted.");
}
private bool TryRegisterFileTransformation()
@@ -125,27 +144,33 @@ public sealed class WebNavInjector : IHostedService
{
Assembly? fileTransformationAssembly = AssemblyLoadContext.All
.SelectMany(context => context.Assemblies)
.FirstOrDefault(assembly => assembly.FullName?.Contains(".FileTransformation", StringComparison.OrdinalIgnoreCase) == true);
.FirstOrDefault(assembly =>
assembly.FullName?.Contains(".FileTransformation", StringComparison.OrdinalIgnoreCase) == true);
if (fileTransformationAssembly is null)
{
return false;
}
Type? pluginInterfaceType = fileTransformationAssembly.GetType("Jellyfin.Plugin.FileTransformation.PluginInterface");
Type? pluginInterfaceType = fileTransformationAssembly.GetType(
"Jellyfin.Plugin.FileTransformation.PluginInterface");
MethodInfo? registerMethod = pluginInterfaceType?.GetMethod(
"RegisterTransformation",
BindingFlags.Public | BindingFlags.Static);
if (registerMethod is null)
{
_logger.LogWarning("File Transformation PluginInterface.RegisterTransformation was not found.");
return false;
}
// Prefer HTTP endpoint: plugin ALC reflection callbacks often fail to resolve.
// Keep callback fields as a secondary path when the host can invoke them.
JObject payload = new()
{
["id"] = TransformationId,
["fileNamePattern"] = @"index\.html",
["transformationEndpoint"] = TransformationEndpoint,
["callbackAssembly"] = typeof(WebNavInjector).Assembly.FullName,
["callbackClass"] = typeof(WebNavInjector).FullName,
["callbackMethod"] = nameof(InjectNavLoader)
@@ -156,7 +181,7 @@ public sealed class WebNavInjector : IHostedService
}
catch (Exception ex)
{
_logger.LogDebug(ex, "File Transformation registration failed.");
_logger.LogWarning(ex, "File Transformation registration failed.");
return false;
}
}
@@ -171,14 +196,13 @@ public sealed class WebNavInjector : IHostedService
}
var html = File.ReadAllText(indexPath);
if (html.Contains(LoaderSrc, StringComparison.Ordinal))
if (html.Contains("/Requests/Assets/nav-loader.js", StringComparison.Ordinal))
{
_logger.LogInformation("Request nav loader already present in {Path}", indexPath);
return;
}
var updated = InjectNavLoader(new IndexHtmlPatchPayload { Contents = html });
File.WriteAllText(indexPath, updated);
File.WriteAllText(indexPath, InjectHtml(html));
_logger.LogInformation("Injected Request nav loader into {Path}", indexPath);
}
@@ -19,15 +19,25 @@ public sealed class MediaRequest
public string MediaType { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the TMDB identifier.
/// Gets or sets the TMDB identifier. Zero for custom titles not found on TMDB.
/// </summary>
public int TmdbId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this was a custom (non-TMDB) request.
/// </summary>
public bool IsCustom { get; set; }
/// <summary>
/// Gets or sets the display title.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets optional notes from the requester (useful for custom titles).
/// </summary>
public string? Notes { get; set; }
/// <summary>
/// Gets or sets the release year when known.
/// </summary>
+84 -17
View File
@@ -3,7 +3,8 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
@@ -19,6 +20,11 @@ public sealed class TmdbClient
/// </summary>
public const string HttpClientName = "Tmdb";
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly IHttpClientFactory _httpClientFactory;
/// <summary>
@@ -42,7 +48,6 @@ public sealed class TmdbClient
string mediaType,
CancellationToken cancellationToken)
{
var apiKey = RequireApiKey();
var path = mediaType switch
{
"movie" => "search/movie",
@@ -50,9 +55,9 @@ public sealed class TmdbClient
_ => "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);
var relativeUrl =
$"{path}?query={Uri.EscapeDataString(query)}&include_adult=false&language=en-US&page=1";
var response = await GetAsync<TmdbSearchResponse>(relativeUrl, cancellationToken).ConfigureAwait(false);
if (response?.Results is null)
{
return [];
@@ -78,13 +83,10 @@ public sealed class TmdbClient
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)}",
var movie = await GetAsync<TmdbMovieDetailResponse>(
$"movie/{tmdbId}?language=en-US",
cancellationToken)
.ConfigureAwait(false);
if (movie is null)
@@ -105,8 +107,8 @@ public sealed class TmdbClient
if (mediaType.Equals("tv", StringComparison.OrdinalIgnoreCase))
{
var show = await client.GetFromJsonAsync<TmdbTvDetailResponse>(
$"tv/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
var show = await GetAsync<TmdbTvDetailResponse>(
$"tv/{tmdbId}?language=en-US",
cancellationToken)
.ConfigureAwait(false);
if (show is null)
@@ -137,15 +139,76 @@ public sealed class TmdbClient
throw new ArgumentException("mediaType must be movie or tv.", nameof(mediaType));
}
private static string RequireApiKey()
private async Task<T?> GetAsync<T>(string relativeUrl, CancellationToken cancellationToken)
{
var apiKey = Plugin.Instance?.Configuration.TmdbApiKey?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(apiKey))
var credential = RequireCredential();
var client = _httpClientFactory.CreateClient(HttpClientName);
var url = credential.UseBearer
? relativeUrl
: AppendQuery(relativeUrl, "api_key", credential.Value);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
if (credential.UseBearer)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", credential.Value);
}
using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(FormatTmdbError(response.StatusCode, body));
}
if (string.IsNullOrWhiteSpace(body))
{
return default;
}
return JsonSerializer.Deserialize<T>(body, JsonOptions);
}
private static string FormatTmdbError(System.Net.HttpStatusCode statusCode, string body)
{
try
{
using var document = JsonDocument.Parse(body);
if (document.RootElement.TryGetProperty("status_message", out var message)
&& message.ValueKind == JsonValueKind.String
&& !string.IsNullOrWhiteSpace(message.GetString()))
{
return $"TMDB {(int)statusCode}: {message.GetString()}";
}
}
catch (JsonException)
{
// Fall through to generic message.
}
return string.IsNullOrWhiteSpace(body)
? $"TMDB request failed with status {(int)statusCode}."
: $"TMDB {(int)statusCode}: {body}";
}
private static string AppendQuery(string relativeUrl, string key, string value)
{
var separator = relativeUrl.Contains('?', StringComparison.Ordinal) ? '&' : '?';
return $"{relativeUrl}{separator}{key}={Uri.EscapeDataString(value)}";
}
private static TmdbCredential RequireCredential()
{
var raw = Plugin.Instance?.Configuration.TmdbApiKey?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(raw))
{
throw new InvalidOperationException("TMDB API key is not configured.");
}
return apiKey;
// TMDB v3 accepts api_key query auth or the API Read Access Token as Bearer.
// https://developer.themoviedb.org/docs/authentication-application
var useBearer = raw.StartsWith("eyJ", StringComparison.Ordinal)
|| (raw.Contains('.', StringComparison.Ordinal) && raw.Length > 40);
return new TmdbCredential(raw, useBearer);
}
private static TmdbSearchItem? MapSearchResult(TmdbRawResult result, string requestedType)
@@ -159,7 +222,9 @@ public sealed class TmdbClient
return null;
}
var title = type == "movie" ? result.Title : result.Name;
var title = type == "movie"
? result.Title ?? result.Name
: result.Name ?? result.Title;
if (string.IsNullOrWhiteSpace(title))
{
return null;
@@ -187,4 +252,6 @@ public sealed class TmdbClient
? year
: null;
}
private readonly record struct TmdbCredential(string Value, bool UseBearer);
}
+449 -185
View File
@@ -1,17 +1,17 @@
(() => {
"use strict";
const REQUEST_URL = "/Requests/Page";
const TAB_ATTR = "data-jellyfin-request-tab";
const STYLE_ID = "jellyfin-plugin-request-nav-style";
const ASSET_CSS = "/Requests/Assets/request.css";
const ASSET_JS = "/Requests/Assets/request.js";
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();
}
let ensuring = null;
let assetsPromise = null;
let guardAttached = false;
let cachedButton = null;
let cachedPanel = null;
let headerObserver = null;
function ensureStyle() {
if (document.getElementById(STYLE_ID)) {
@@ -20,37 +20,314 @@
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}";
style.textContent = [
".jf-request-tab-panel{padding:1rem 1.25rem 2rem;box-sizing:border-box;min-height:50vh;}",
".jf-request-tab-panel .req-embed{max-width:1400px;margin:0 auto;}",
`.headerTabs .emby-tab-button[${TAB_ATTR}].jf-request-tab-away{display:none!important;}`,
".jf-request-menu-item{align-items:center;color:inherit;display:flex!important;gap:1rem;min-height:3rem;padding:.75rem 1.25rem;text-decoration:none;cursor:pointer;background:none;border:0;width:100%;text-align:left;font:inherit;}",
".jf-request-menu-item:hover,.jf-request-menu-item:focus{color:#00a4dc;}",
".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;}"
].join("");
document.head.appendChild(style);
}
function controlsIn(container) {
return Array.from(container.querySelectorAll("a, button, [role='button'], [role='menuitem'], [role='link']"));
function isHomeTabContext() {
const hash = (window.location.hash || "").toLowerCase();
const onHomeHash = hash === ""
|| hash === "#"
|| hash === "#/home"
|| hash === "#/home.html"
|| hash === "#home"
|| hash.indexOf("#/home?") === 0
|| hash.indexOf("#/home.html?") === 0
|| hash.indexOf("#home?") === 0;
if (!onHomeHash) {
return false;
}
function openRequestPage(event) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation?.();
window.location.assign(REQUEST_URL);
const page = document.getElementById("indexPage");
if (!page || page.classList.contains("hide")) {
return false;
}
function wireLink(link) {
link.href = REQUEST_URL;
link.addEventListener("click", openRequestPage, true);
return link;
const visiblePage = document.querySelector(".page:not(.hide)");
return !visiblePage || visiblePage.id === "indexPage";
}
function labelMatches(node, labels) {
const label = textOf(node);
return labels.some((value) => label === value || label.includes(value));
function loadAssets() {
if (assetsPromise) {
return assetsPromise;
}
function isDrawerElement(node) {
return Boolean(node?.closest?.(".mainDrawer,.mainDrawer-scrollContainer,.drawerContent,.MuiDrawer-paper"));
assetsPromise = new Promise((resolve, reject) => {
if (!document.querySelector(`link[href="${ASSET_CSS}"]`)) {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = ASSET_CSS;
document.head.appendChild(link);
}
function sideMenuContainers() {
if (window.JellyfinRequestUI) {
resolve();
return;
}
const existing = document.querySelector(`script[src="${ASSET_JS}"]`);
if (existing) {
existing.addEventListener("load", () => resolve(), { once: true });
existing.addEventListener("error", () => reject(new Error("Failed to load request.js")), { once: true });
return;
}
const script = document.createElement("script");
script.src = ASSET_JS;
script.onload = () => resolve();
script.onerror = () => reject(new Error("Failed to load request.js"));
document.head.appendChild(script);
});
return assetsPromise;
}
function createTabButton() {
const titleEl = document.createElement("div");
titleEl.className = "emby-button-foreground";
titleEl.textContent = "Request";
const button = document.createElement("button");
button.type = "button";
button.setAttribute("is", "empty-button");
button.className = "emby-tab-button emby-button";
button.setAttribute(TAB_ATTR, "request");
button.setAttribute("aria-label", "Request");
button.appendChild(titleEl);
return button;
}
function createTabPanel() {
const panel = document.createElement("div");
panel.className = "tabContent pageTabContent hide jf-request-tab-panel";
panel.setAttribute(TAB_ATTR, "request");
panel.id = "jellyfinRequestTab";
const mount = document.createElement("div");
mount.className = "sections jf-request-sections";
mount.setAttribute("data-role", "request-mount");
panel.appendChild(mount);
return panel;
}
function bindRequestButton(button) {
if (!button || button.dataset.jfRequestClickBound === "1") {
return;
}
button.dataset.jfRequestClickBound = "1";
button.addEventListener("click", () => {
setTimeout(showRequestPanel, 0);
setTimeout(showRequestPanel, 120);
});
}
function findNativeButtons(tabsSlider) {
return Array.from(tabsSlider.querySelectorAll(".emby-tab-button")).filter((btn) => {
if (btn.hasAttribute(TAB_ATTR)) {
return false;
}
const id = btn.id || "";
return id.indexOf("customTabButton_") !== 0;
});
}
function placeInOrder(parent, nodes) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const previous = i > 0 ? nodes[i - 1] : null;
if (!previous) {
if (node.parentNode !== parent) {
parent.appendChild(node);
}
continue;
}
const alreadyAfter = node.parentNode === parent
&& (previous.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
if (!alreadyAfter) {
parent.insertBefore(node, previous.nextSibling);
}
}
}
function syncIndexes(tabsSlider, page) {
const buttons = Array.from(tabsSlider.querySelectorAll(".emby-tab-button"))
.filter((button) => !button.classList.contains("jf-request-tab-away"));
buttons.forEach((button, index) => {
button.setAttribute("data-index", String(index));
const key = button.getAttribute(TAB_ATTR);
if (key) {
const panel = page.querySelector(`.tabContent[${TAB_ATTR}="${key}"]`);
if (panel) {
panel.setAttribute("data-index", String(index));
}
return;
}
if (index === 0) {
page.querySelector("#homeTab")?.setAttribute("data-index", "0");
} else if (index === 1) {
page.querySelector("#favoritesTab")?.setAttribute("data-index", "1");
}
});
}
function syncPanelVisibility(selectedIndex) {
const page = document.getElementById("indexPage");
if (!page || isNaN(selectedIndex)) {
return;
}
page.querySelectorAll(".tabContent[data-index]").forEach((panel) => {
const panelIndex = parseInt(panel.getAttribute("data-index"), 10);
const active = panelIndex === selectedIndex;
panel.classList.toggle("hide", !active);
panel.classList.toggle("is-active", active);
});
}
async function mountRequestUi(panel, forceRemount) {
if (!panel) {
return;
}
panel.classList.remove("hide");
panel.classList.add("is-active");
const mount = panel.querySelector('[data-role="request-mount"]');
if (!mount) {
return;
}
try {
await loadAssets();
} catch (error) {
mount.textContent = "Failed to load Request UI.";
console.error("[Jellyfin.Plugin.Request]", error);
return;
}
if (!window.JellyfinRequestUI) {
mount.textContent = "Request UI failed to initialize.";
return;
}
const needsForce = forceRemount || !mount.querySelector(".req-root");
window.JellyfinRequestUI.mount(mount, { embed: true, force: needsForce });
}
function showRequestPanel() {
const page = document.getElementById("indexPage");
const button = document.querySelector(`.headerTabs [${TAB_ATTR}="request"]`);
const panel = page?.querySelector(`.tabContent[${TAB_ATTR}="request"]`) || cachedPanel;
if (!button || !panel) {
return;
}
const index = parseInt(button.getAttribute("data-index"), 10);
if (!isNaN(index)) {
syncPanelVisibility(index);
} else {
panel.classList.remove("hide");
panel.classList.add("is-active");
}
mountRequestUi(panel, true);
}
function isRequestTabButton(button) {
return !!(button && button.getAttribute(TAB_ATTR) === "request");
}
function hideRequestTabAway() {
// Hide instead of remove so returning to Home can restore without a visible gap.
document.querySelectorAll(`.headerTabs [${TAB_ATTR}]`).forEach((node) => {
node.classList.add("jf-request-tab-away");
node.setAttribute("aria-hidden", "true");
if (!cachedButton && node.matches(".emby-tab-button")) {
cachedButton = node;
}
});
}
function attachPluginTabGuard(tabsEl) {
if (!tabsEl || tabsEl.dataset.jfRequestTabGuard === "true") {
return;
}
tabsEl.dataset.jfRequestTabGuard = "true";
guardAttached = true;
tabsEl.addEventListener("beforetabchange", (event) => {
if (!isHomeTabContext()) {
return;
}
const index = parseInt(event.detail && event.detail.selectedTabIndex, 10);
if (isNaN(index)) {
return;
}
syncPanelVisibility(index);
const selectedButton = tabsEl.querySelector(`.emby-tab-button[data-index="${index}"]`);
if (isRequestTabButton(selectedButton)) {
const panel = document.querySelector(`.tabContent[${TAB_ATTR}="request"]`) || cachedPanel;
mountRequestUi(panel, false);
}
}, true);
tabsEl.addEventListener("tabchange", (event) => {
if (!isHomeTabContext()) {
return;
}
const index = parseInt(event.detail && event.detail.selectedTabIndex, 10);
if (isNaN(index)) {
return;
}
const selectedButton = tabsEl.querySelector(`.emby-tab-button[data-index="${index}"]`);
if (!isRequestTabButton(selectedButton)) {
return;
}
event.stopImmediatePropagation();
syncPanelVisibility(index);
const panel = document.querySelector(`.tabContent[${TAB_ATTR}="request"]`) || cachedPanel;
mountRequestUi(panel, true);
}, true);
}
function activateRequestTab() {
if (!isHomeTabContext()) {
window.location.hash = "#/home";
setTimeout(activateRequestTab, 250);
return;
}
ensureRequestTab().then(() => {
const button = document.querySelector(`.headerTabs [${TAB_ATTR}="request"]`);
if (button) {
button.click();
}
});
}
function insertSideMenuItem() {
ensureStyle();
const selectors = [
".mainDrawer-scrollContainer",
".mainDrawer .scrollContainer",
@@ -58,168 +335,37 @@
".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()) {
for (const container of document.querySelectorAll(selector)) {
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"))
const controls = Array.from(container.querySelectorAll("a, button, [role='button'], [role='menuitem']"));
const labels = controls.map((node) => (node.textContent || "").trim().toLowerCase());
if (!labels.some((label) => label === "home" || label.includes("home"))) {
continue;
}
const after = controls.find((item) => /^(favorites|favourites)$/i.test((item.textContent || "").trim()))
|| controls.find((item) => /home/i.test(item.textContent || ""))
|| controls[0];
if (!after) {
continue;
}
const link = createMenuItem(after);
const link = document.createElement("button");
link.type = "button";
link.className = `${after.className || ""} jf-request-menu-item`.trim();
link.setAttribute("aria-label", "Request");
link.innerHTML = '<span class="material-icons jf-request-menu-icon" aria-hidden="true">add_circle_outline</span><span class="jf-request-menu-label">Request</span>';
link.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
activateRequestTab();
});
if (after.parentElement === container) {
after.insertAdjacentElement("afterend", link);
} else {
@@ -227,13 +373,131 @@
}
}
}
function insertEntries() {
insertTopTab();
insertSideMenuItem();
}
insertEntries();
setInterval(insertEntries, 1000);
new MutationObserver(insertEntries).observe(document.documentElement, { childList: true, subtree: true });
function ensureRequestTab() {
if (ensuring) {
return ensuring;
}
ensuring = (async () => {
ensureStyle();
insertSideMenuItem();
if (!isHomeTabContext()) {
hideRequestTabAway();
return;
}
const page = document.getElementById("indexPage");
const tabsSlider = document.querySelector(".headerTabs .emby-tabs-slider");
const tabsEl = document.querySelector('.headerTabs [is="emby-tabs"]');
if (!page || !tabsSlider || !tabsEl) {
return;
}
const homeTab = page.querySelector("#homeTab");
const favoritesTab = page.querySelector("#favoritesTab");
if (!homeTab || !favoritesTab) {
return;
}
attachPluginTabGuard(tabsEl);
let button = tabsSlider.querySelector(`[${TAB_ATTR}="request"]`)
|| (cachedButton && cachedButton.isConnected ? cachedButton : null)
|| cachedButton;
if (!button || !button.isConnected) {
button = createTabButton();
}
cachedButton = button;
button.classList.remove("jf-request-tab-away", "hide");
button.removeAttribute("aria-hidden");
bindRequestButton(button);
let panel = page.querySelector(`.tabContent[${TAB_ATTR}="request"]`)
|| (cachedPanel && cachedPanel.isConnected ? cachedPanel : null)
|| cachedPanel;
if (!panel || !panel.isConnected) {
panel = createTabPanel();
}
cachedPanel = panel;
// Insert the tab button before any async work so Home return does not flash without it.
const nativeButtons = findNativeButtons(tabsSlider);
const homeButton = nativeButtons[0];
const favoritesButton = nativeButtons[1] || nativeButtons[0];
const orderedButtons = [homeButton, favoritesButton, button].filter(Boolean);
const uniqueButtons = [...new Set(orderedButtons)];
placeInOrder(tabsSlider, uniqueButtons);
const orderedPanels = [homeTab, favoritesTab, panel];
placeInOrder(page, orderedPanels);
syncIndexes(tabsSlider, page);
if (typeof tabsEl.refresh === "function") {
try {
tabsEl.refresh();
} catch {
// best-effort
}
}
loadAssets().catch(() => { /* surfaced on mount */ });
})().finally(() => {
ensuring = null;
});
return ensuring;
}
function observeHeaderTabs() {
const headerTabs = document.querySelector(".headerTabs");
if (!headerTabs || headerObserver) {
return;
}
let timer = null;
headerObserver = new MutationObserver(() => {
const onHome = isHomeTabContext();
const missing = onHome && !document.querySelector(`.headerTabs [${TAB_ATTR}="request"]:not(.jf-request-tab-away)`);
if (missing) {
// Jellyfin rebuilt the home tab bar — reinject immediately to avoid flicker.
ensureRequestTab();
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => ensureRequestTab(), 80);
});
headerObserver.observe(headerTabs, { childList: true, subtree: true });
}
function boot() {
console.info("[Jellyfin.Plugin.Request] nav-loader active");
ensureRequestTab();
observeHeaderTabs();
document.addEventListener("viewshow", (event) => {
if (event.target && event.target.id === "indexPage") {
ensureRequestTab();
} else {
hideRequestTabAway();
}
});
window.addEventListener("hashchange", () => ensureRequestTab());
setInterval(() => ensureRequestTab(), 2500);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot);
} else {
boot();
}
})();
+66 -6
View File
@@ -10,21 +10,32 @@
--req-warn: #f0ad4e;
}
* {
.req-root,
.req-root * {
box-sizing: border-box;
}
html,
body {
body.jellyfin-request-standalone {
margin: 0;
min-height: 100%;
padding: 1.25rem;
background: var(--req-bg);
color: var(--req-text);
font-family: Inherit, "Segoe UI", Roboto, sans-serif;
}
body {
padding: 1.25rem;
.req-root {
color: var(--req-text);
font-family: Inherit, "Segoe UI", Roboto, sans-serif;
}
.req-embed {
background: transparent;
padding: 0;
}
.req-embed .req-title {
font-size: 1.35rem;
}
.req-header {
@@ -82,7 +93,21 @@ body {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-bottom: 1rem;
margin-bottom: 0.75rem;
}
.req-search-meta {
margin: 0 0 1rem;
}
.req-card-placeholder {
aspect-ratio: 2 / 3;
display: flex;
align-items: center;
justify-content: center;
background: #000;
padding: 0.75rem;
text-align: center;
}
.req-search-row input[type="search"] {
@@ -230,6 +255,41 @@ body {
.req-badge.approved { background: #0f3d1f; color: #8dffb0; }
.req-badge.rejected { background: #4a1212; color: #ff9d9d; }
.req-badge.fulfilled { background: #0a3345; color: #8ad7ff; }
.req-badge.custom { background: #3a2a55; color: #d7b8ff; margin-left: 0.35rem; }
.req-custom-form {
display: flex;
flex-direction: column;
gap: 0.85rem;
max-width: 560px;
margin-top: 1rem;
}
.req-field {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.req-field span {
color: var(--req-muted);
font-size: 0.9rem;
}
.req-field input,
.req-field textarea {
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-field textarea {
resize: vertical;
min-height: 5rem;
}
.req-list-actions {
display: flex;
+481 -103
View File
@@ -1,32 +1,90 @@
(() => {
"use strict";
const API = "/Requests";
const state = {
mediaType: "multi",
status: null,
isAdmin: false,
detail: null,
requests: []
};
function apiRoot() {
try {
if (typeof ApiClient !== "undefined" && typeof ApiClient.serverAddress === "function") {
const base = String(ApiClient.serverAddress() || "").replace(/\/+$/, "");
if (base) {
return `${base}/Requests`;
}
}
} catch {
// Fall through.
}
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")
};
return "/Requests";
}
const MARKUP = `
<div class="req-root">
<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="custom">Custom</button>
<button type="button" class="req-tab" data-view="mine">My requests</button>
<button type="button" class="req-tab req-hidden" data-view="admin" data-role="admin-tab">Admin queue</button>
</nav>
</header>
<div class="req-status-banner req-hidden" data-role="status-banner"></div>
<p class="req-message req-hidden" data-role="global-message"></p>
<section data-role="search-view">
<div class="req-search-row">
<input data-role="search-input" type="search" placeholder="Search movies or TV shows on TMDB" 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" data-role="search-btn">Search</button>
</div>
<p class="req-search-meta req-muted req-hidden" data-role="search-meta"></p>
<div class="req-grid" data-role="results"></div>
<div class="req-detail req-hidden" data-role="detail"></div>
</section>
<section class="req-hidden" data-role="custom-view">
<p class="req-muted">Can’t find it on TMDB? Submit a custom movie or TV request for the admin to review.</p>
<form class="req-custom-form" data-role="custom-form">
<label class="req-field">
<span>Title</span>
<input data-role="custom-title" type="text" maxlength="200" required placeholder="Exact title" autocomplete="off" />
</label>
<div class="req-type-toggle" role="group" aria-label="Custom media type">
<button type="button" class="req-type-btn active" data-role="custom-type" data-type="movie">Movie</button>
<button type="button" class="req-type-btn" data-role="custom-type" data-type="tv">TV</button>
</div>
<label class="req-field">
<span>Year (optional)</span>
<input data-role="custom-year" type="number" min="1870" max="2100" placeholder="e.g. 2024" />
</label>
<label class="req-field">
<span>Notes (optional)</span>
<textarea data-role="custom-notes" rows="3" maxlength="1000" placeholder="Links, alternate titles, quality, seasons…"></textarea>
</label>
<button type="submit" class="req-btn primary" data-role="custom-submit">Submit custom request</button>
</form>
</section>
<section class="req-hidden" data-role="mine-view">
<div class="req-list" data-role="mine-list"></div>
</section>
<section class="req-hidden" data-role="admin-view">
<div class="req-list" data-role="admin-list"></div>
</section>
</div>`;
function authHeader() {
try {
if (typeof ApiClient !== "undefined" && ApiClient.accessToken) {
const token = ApiClient.accessToken();
if (token) {
return {
Authorization: `MediaBrowser Client="Request Plugin", Device="Browser", DeviceId="jellyfin-plugin-request", Version="1.0.0", Token="${token}"`,
"X-Emby-Token": token
};
}
}
const raw = localStorage.getItem("jellyfin_credentials");
const credentials = raw ? JSON.parse(raw) : null;
const server = credentials?.Servers?.find((item) => item.AccessToken) || credentials?.Servers?.[0];
@@ -47,14 +105,30 @@
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}`;
const data = JSON.parse(text);
if (data.message) {
return data.message;
}
if (data.errors && typeof data.errors === "object") {
const details = Object.values(data.errors).flat().filter(Boolean);
if (details.length) {
return details.join(" ");
}
}
if (data.title) {
return data.status ? `${data.title} (${data.status})` : data.title;
}
} catch {
// Fall through.
}
return text || `${response.status} ${response.statusText}`;
}
async function api(path, options = {}) {
const response = await fetch(`${API}${path}`, {
const response = await fetch(`${apiRoot()}${path}`, {
cache: "no-store",
...options,
headers: {
@@ -75,28 +149,72 @@
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") {
if (typeof value === "string" && value) {
return value;
}
return ["Pending", "Approved", "Rejected", "Fulfilled"][value] || "Unknown";
if (typeof value === "number" && value >= 0 && value <= 3) {
return ["Pending", "Approved", "Rejected", "Fulfilled"][value];
}
return "Unknown";
}
function statusClass(value) {
return statusName(value).toLowerCase();
}
function normalizeRequest(item) {
if (!item || typeof item !== "object") {
return {
id: "",
mediaType: "",
title: "Untitled",
year: null,
posterPath: null,
seasons: [],
allSeasons: false,
requestedByName: "Unknown",
createdAtUtc: null,
status: "Unknown",
adminNote: null
};
}
const tmdbId = Number(item.tmdbId ?? item.TmdbId ?? 0);
const isCustom = !!(item.isCustom ?? item.IsCustom) || tmdbId <= 0;
return {
id: item.id ?? item.Id ?? "",
mediaType: item.mediaType || item.MediaType || "",
title: item.title || item.Title || "Untitled",
year: item.year ?? item.Year ?? null,
posterPath: item.posterPath || item.PosterPath || null,
seasons: item.seasons || item.Seasons || [],
allSeasons: !!(item.allSeasons ?? item.AllSeasons),
requestedByName: item.requestedByName || item.RequestedByName || "Unknown",
createdAtUtc: item.createdAtUtc || item.CreatedAtUtc || null,
status: item.status ?? item.Status,
adminNote: item.adminNote || item.AdminNote || null,
notes: item.notes || item.Notes || null,
isCustom,
tmdbId
};
}
function formatRequestDate(value) {
if (!value) {
return "Unknown date";
}
const date = new Date(value);
return Number.isNaN(date.getTime()) ? "Unknown date" : date.toLocaleString();
}
function escapeHtml(value) {
return String(value ?? "")
.replaceAll("&", "&amp;")
@@ -105,14 +223,68 @@
.replaceAll('"', "&quot;");
}
function createController(root) {
const state = {
mediaType: "multi",
customMediaType: "movie",
status: null,
isAdmin: false,
detail: null,
requests: []
};
const els = {
root,
statusBanner: root.querySelector('[data-role="status-banner"]'),
globalMessage: root.querySelector('[data-role="global-message"]'),
searchInput: root.querySelector('[data-role="search-input"]'),
searchBtn: root.querySelector('[data-role="search-btn"]'),
searchMeta: root.querySelector('[data-role="search-meta"]'),
results: root.querySelector('[data-role="results"]'),
detail: root.querySelector('[data-role="detail"]'),
customForm: root.querySelector('[data-role="custom-form"]'),
customTitle: root.querySelector('[data-role="custom-title"]'),
customYear: root.querySelector('[data-role="custom-year"]'),
customNotes: root.querySelector('[data-role="custom-notes"]'),
customSubmit: root.querySelector('[data-role="custom-submit"]'),
mineList: root.querySelector('[data-role="mine-list"]'),
adminList: root.querySelector('[data-role="admin-list"]'),
adminTab: root.querySelector('[data-role="admin-tab"]'),
searchView: root.querySelector('[data-role="search-view"]'),
customView: root.querySelector('[data-role="custom-view"]'),
mineView: root.querySelector('[data-role="mine-view"]'),
adminView: root.querySelector('[data-role="admin-view"]')
};
function showMessage(text, isError) {
els.globalMessage.textContent = text;
els.globalMessage.classList.toggle("req-hidden", !text);
els.globalMessage.classList.toggle("req-error", !!isError);
}
function applyAdminUi() {
els.adminTab.classList.toggle("req-hidden", !state.isAdmin);
if (!state.isAdmin) {
els.adminList.innerHTML = "";
if (!els.adminView.classList.contains("req-hidden")) {
setView("mine");
}
}
}
function setView(view) {
document.querySelectorAll(".req-tab").forEach((tab) => {
if (view === "admin" && !state.isAdmin) {
view = "mine";
}
root.querySelectorAll(".req-tab").forEach((tab) => {
tab.classList.toggle("active", tab.dataset.view === view);
});
els.searchView.classList.toggle("req-hidden", view !== "search");
els.customView.classList.toggle("req-hidden", view !== "custom");
els.mineView.classList.toggle("req-hidden", view !== "mine");
els.adminView.classList.toggle("req-hidden", view !== "admin");
if (view === "mine" || view === "admin") {
if (view === "mine" || (view === "admin" && state.isAdmin)) {
loadRequests();
}
}
@@ -120,10 +292,15 @@
async function loadStatus() {
try {
state.status = await api("/Status");
if (!state.status.isConfigured) {
const configured = !!(state.status.isConfigured ?? state.status.IsConfigured);
const submissionsEnabled = !!(state.status.requestSubmissionEnabled ?? state.status.RequestSubmissionEnabled);
state.isAdmin = !!(state.status.isAdmin ?? state.status.IsAdmin);
applyAdminUi();
if (!configured) {
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) {
} else if (!submissionsEnabled) {
els.statusBanner.textContent = "Search is available. Request submission is disabled by the administrator.";
els.statusBanner.classList.remove("req-hidden");
} else {
@@ -136,7 +313,12 @@
async function loadCurrentUser() {
try {
const response = await fetch("/Users/Me", {
let me = null;
if (typeof ApiClient !== "undefined" && typeof ApiClient.getCurrentUser === "function") {
me = await ApiClient.getCurrentUser();
} else {
const base = apiRoot().replace(/\/Requests$/, "");
const response = await fetch(`${base}/Users/Me`, {
cache: "no-store",
headers: authHeader()
});
@@ -144,42 +326,84 @@
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.
me = await response.json();
}
const policy = me?.Policy || me?.policy || {};
const fromUser = !!(policy.IsAdministrator ?? policy.isAdministrator);
if (fromUser) {
state.isAdmin = true;
}
applyAdminUi();
} catch {
// Non-fatal; Status endpoint remains the source of truth.
}
}
function setSearchMeta(text) {
if (!els.searchMeta) {
return;
}
els.searchMeta.textContent = text || "";
els.searchMeta.classList.toggle("req-hidden", !text);
}
async function runSearch() {
const query = els.searchInput.value.trim();
if (!query) {
showMessage("Enter a search query.", true);
setSearchMeta("");
return;
}
showMessage("Searching…");
if (state.status && !state.status.isConfigured) {
showMessage("TMDB is not configured. Set a TMDB API key or Read Access Token in Dashboard → Plugins → Request.", true);
return;
}
showMessage("");
setSearchMeta(`Searching TMDB for “${query}”…`);
els.searchBtn.disabled = true;
els.detail.classList.add("req-hidden");
els.results.classList.remove("req-hidden");
els.results.innerHTML = "";
try {
const results = await api(`/Search?query=${encodeURIComponent(query)}&type=${encodeURIComponent(state.mediaType)}`);
showMessage(results.length ? "" : "No results found.");
renderResults(results);
const list = Array.isArray(results) ? results : [];
setSearchMeta(list.length
? `Showing ${list.length} result${list.length === 1 ? "" : "s"} for “${query}”`
: `No TMDB results for “${query}”`);
showMessage(list.length ? "" : "No movies or TV shows matched that search.");
renderResults(list);
} catch (error) {
setSearchMeta(`Search failed for “${query}”`);
showMessage(error.message, true);
els.results.innerHTML = "";
} finally {
els.searchBtn.disabled = false;
}
}
function renderResults(results) {
if (!results.length) {
els.results.innerHTML = "";
return;
}
els.results.innerHTML = results.map((item) => {
const img = item.posterUrl || posterUrl(item.posterPath);
const mediaType = item.mediaType || item.MediaType || "";
const tmdbId = item.tmdbId ?? item.TmdbId;
const title = item.title || item.Title || "Untitled";
const year = item.year ?? item.Year;
const img = item.posterUrl || item.PosterUrl || posterUrl(item.posterPath || 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>`}
<article class="req-card" data-type="${escapeHtml(mediaType)}" data-id="${escapeHtml(tmdbId)}">
${img ? `<img src="${escapeHtml(img)}" alt="${escapeHtml(title)}" loading="lazy" />` : `<div class="req-card-placeholder"><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>
<p class="req-card-title">${escapeHtml(title)}</p>
<p class="req-muted">${escapeHtml(mediaType)}${year ? ` · ${escapeHtml(year)}` : ""}</p>
</div>
</article>`;
}).join("");
@@ -202,18 +426,28 @@
}
function renderDetail(detail) {
const img = detail.posterUrl || posterUrl(detail.posterPath, 500);
const allowSeasons = state.status?.allowSeasonSelection !== false && detail.mediaType === "tv";
const mediaType = detail.mediaType || detail.MediaType || "";
const title = detail.title || detail.Title || "Untitled";
const year = detail.year ?? detail.Year;
const overview = detail.overview || detail.Overview || "No overview available.";
const seasons = detail.seasons || detail.Seasons || [];
const img = detail.posterUrl || detail.PosterUrl || posterUrl(detail.posterPath || detail.PosterPath, 500);
const allowSeasons = state.status?.allowSeasonSelection !== false && 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" data-role="all-seasons" checked /> All seasons</label>
${seasons.map((season) => {
const seasonNumber = season.seasonNumber ?? season.SeasonNumber;
const seasonName = season.name || season.Name || `Season ${seasonNumber}`;
const episodeCount = season.episodeCount ?? season.EpisodeCount ?? 0;
return `
<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("")}
<input type="checkbox" class="season-box" value="${escapeHtml(seasonNumber)}" disabled />
${escapeHtml(seasonName)} <span class="req-muted">(${escapeHtml(episodeCount)})</span>
</label>`;
}).join("")}
</div>`
: detail.mediaType === "tv"
: mediaType === "tv"
? `<p class="req-muted">This request will cover all seasons.</p>`
: "";
@@ -221,28 +455,28 @@
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>
<button type="button" class="req-btn" data-role="back-results">Back to results</button>
<h2 class="req-detail-title">${escapeHtml(title)}</h2>
<p class="req-muted">${escapeHtml(mediaType)}${year ? ` · ${escapeHtml(year)}` : ""}</p>
<p>${escapeHtml(overview)}</p>
${seasonHtml}
<div class="req-detail-actions">
<button type="button" class="req-btn primary" id="submitRequest" ${state.status?.requestSubmissionEnabled ? "" : "disabled"}>
<button type="button" class="req-btn primary" data-role="submit-request" ${state.status?.requestSubmissionEnabled ? "" : "disabled"}>
Request
</button>
</div>
</div>`;
els.results.classList.add("req-hidden");
document.getElementById("backToResults").addEventListener("click", () => {
els.detail.querySelector('[data-role="back-results"]').addEventListener("click", () => {
els.detail.classList.add("req-hidden");
els.results.classList.remove("req-hidden");
});
const allSeasons = document.getElementById("allSeasons");
const allSeasons = els.detail.querySelector('[data-role="all-seasons"]');
if (allSeasons) {
allSeasons.addEventListener("change", () => {
document.querySelectorAll(".season-box").forEach((box) => {
els.detail.querySelectorAll(".season-box").forEach((box) => {
box.disabled = allSeasons.checked;
if (allSeasons.checked) {
box.checked = false;
@@ -251,20 +485,34 @@
});
}
document.getElementById("submitRequest").addEventListener("click", () => submitRequest(detail));
els.detail.querySelector('[data-role="submit-request"]').addEventListener("click", () => submitRequest(detail));
}
async function submitRequest(detail) {
const mediaType = detail.mediaType || detail.MediaType || "";
const tmdbId = Number(detail.tmdbId ?? detail.TmdbId);
const title = detail.title || detail.Title || "Untitled";
if ((mediaType !== "movie" && mediaType !== "tv") || !Number.isFinite(tmdbId) || tmdbId < 1) {
showMessage("Could not read this title’s TMDB id. Go back and open it again.", true);
return;
}
if (state.status && !state.status.requestSubmissionEnabled) {
showMessage("Request submission is disabled. Enable it in Dashboard → Plugins → Request.", true);
return;
}
const payload = {
mediaType: detail.mediaType,
tmdbId: detail.tmdbId,
mediaType,
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));
const allSeasons = els.detail.querySelector('[data-role="all-seasons"]');
if (mediaType === "tv" && allSeasons && !allSeasons.checked) {
const selected = Array.from(els.detail.querySelectorAll(".season-box:checked")).map((box) => Number(box.value));
if (!selected.length) {
showMessage("Select at least one season, or choose all seasons.", true);
return;
@@ -276,7 +524,7 @@
try {
await api("", { method: "POST", body: JSON.stringify(payload) });
showMessage(`Requested “${detail.title}”.`);
showMessage(`Requested “${title}”.`);
} catch (error) {
showMessage(error.message, true);
}
@@ -284,13 +532,16 @@
async function loadRequests() {
try {
state.requests = await api("");
const raw = await api("");
state.requests = (Array.isArray(raw) ? raw : []).map(normalizeRequest);
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);
const aTime = a.createdAtUtc ? new Date(a.createdAtUtc).getTime() : 0;
const bTime = b.createdAtUtc ? new Date(b.createdAtUtc).getTime() : 0;
return aPending - bPending || bTime - aTime;
});
renderRequestList(els.adminList, pendingFirst, true);
}
@@ -300,36 +551,42 @@
}
function renderRequestList(container, items, adminMode) {
const showAdminActions = !!(adminMode && state.isAdmin);
if (!items.length) {
container.innerHTML = `<p class="req-message">No requests yet.</p>`;
return;
}
container.innerHTML = items.map((item) => {
container.innerHTML = items.map((raw) => {
const item = normalizeRequest(raw);
const img = posterUrl(item.posterPath, 185);
const seasons = item.allSeasons
? "All seasons"
: (item.seasons || []).length
? `Seasons ${(item.seasons || []).join(", ")}`
: 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>`
: "");
const status = statusName(item.status);
const requestId = String(item.id || "");
let actions = "";
if (showAdminActions && requestId) {
actions = `
<button type="button" class="req-btn" data-action="approve" data-id="${escapeHtml(requestId)}">Approve</button>
<button type="button" class="req-btn" data-action="reject" data-id="${escapeHtml(requestId)}">Reject</button>
<button type="button" class="req-btn" data-action="fulfill" data-id="${escapeHtml(requestId)}">Fulfilled</button>
<button type="button" class="req-btn danger" data-action="delete" data-id="${escapeHtml(requestId)}">Delete</button>`;
} else if (!showAdminActions && status === "Pending" && requestId) {
actions = `<button type="button" class="req-btn danger" data-action="delete" data-id="${escapeHtml(requestId)}">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>
<p class="req-card-title">${escapeHtml(item.title)}${item.isCustom ? ' <span class="req-badge custom">Custom</span>' : ""}</p>
<p class="req-muted">${escapeHtml(item.mediaType)}${item.year ? ` · ${escapeHtml(item.year)}` : ""}${seasons ? ` · ${escapeHtml(seasons)}` : ""}</p>
<p class="req-muted">Requested by ${escapeHtml(item.requestedByName)} · ${escapeHtml(formatRequestDate(item.createdAtUtc))}</p>
<span class="req-badge ${statusClass(item.status)}">${escapeHtml(status)}</span>
${item.notes ? `<p class="req-muted">Notes: ${escapeHtml(item.notes)}</p>` : ""}
${item.adminNote ? `<p class="req-muted">${escapeHtml(item.adminNote)}</p>` : ""}
</div>
<div class="req-list-actions">${actions}</div>
@@ -337,37 +594,74 @@
}).join("");
container.querySelectorAll("[data-action]").forEach((button) => {
button.addEventListener("click", () => handleRequestAction(button.dataset.action, button.dataset.id));
button.addEventListener("click", () => handleRequestAction(button.dataset.action, button.dataset.id, showAdminActions));
});
}
async function handleRequestAction(action, id) {
async function handleRequestAction(action, id, fromAdminQueue) {
const requestId = String(id || "").trim();
if (!requestId) {
showMessage("Missing request id.", true);
return;
}
const adminActions = new Set(["approve", "reject", "fulfill"]);
if ((adminActions.has(action) || (action === "delete" && fromAdminQueue)) && !state.isAdmin) {
showMessage("Administrator access is required.", true);
return;
}
if (action === "delete" && !window.confirm(fromAdminQueue ? "Delete this request?" : "Cancel this request?")) {
return;
}
const messages = {
approve: "Request approved.",
reject: "Request rejected.",
fulfill: "Request marked fulfilled.",
delete: fromAdminQueue ? "Request deleted." : "Request canceled."
};
try {
if (action === "delete") {
await api(`/${id}`, { method: "DELETE" });
await api(`/${encodeURIComponent(requestId)}`, { method: "DELETE" });
} else if (adminActions.has(action)) {
await api(`/${encodeURIComponent(requestId)}/${action}`, {
method: "POST",
body: JSON.stringify({ adminNote: null })
});
} else {
await api(`/${id}/${action}`, { method: "POST", body: "{}" });
showMessage("Unknown action.", true);
return;
}
await loadRequests();
showMessage("Updated.");
showMessage(messages[action] || "Updated.");
} catch (error) {
showMessage(error.message, true);
}
}
document.querySelectorAll(".req-tab").forEach((tab) => {
root.querySelectorAll(".req-tab").forEach((tab) => {
tab.addEventListener("click", () => setView(tab.dataset.view));
});
document.querySelectorAll(".req-type-btn").forEach((button) => {
els.searchView.querySelectorAll(".req-type-btn").forEach((button) => {
button.addEventListener("click", () => {
document.querySelectorAll(".req-type-btn").forEach((item) => item.classList.remove("active"));
els.searchView.querySelectorAll(".req-type-btn").forEach((item) => item.classList.remove("active"));
button.classList.add("active");
state.mediaType = button.dataset.type;
});
});
root.querySelectorAll('[data-role="custom-type"]').forEach((button) => {
button.addEventListener("click", () => {
root.querySelectorAll('[data-role="custom-type"]').forEach((item) => item.classList.remove("active"));
button.classList.add("active");
state.customMediaType = button.dataset.type;
});
});
els.searchBtn.addEventListener("click", runSearch);
els.searchInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
@@ -375,6 +669,90 @@
}
});
loadStatus();
loadCurrentUser();
els.customForm.addEventListener("submit", async (event) => {
event.preventDefault();
const title = els.customTitle.value.trim();
if (!title) {
showMessage("Enter a title for the custom request.", true);
return;
}
if (state.status && !(state.status.requestSubmissionEnabled ?? state.status.RequestSubmissionEnabled)) {
showMessage("Request submission is disabled. Enable it in Dashboard → Plugins → Request.", true);
return;
}
const yearRaw = els.customYear.value.trim();
const year = yearRaw ? Number(yearRaw) : null;
if (yearRaw && (!Number.isFinite(year) || year < 1870 || year > 2100)) {
showMessage("Year must be between 1870 and 2100.", true);
return;
}
els.customSubmit.disabled = true;
try {
await api("", {
method: "POST",
body: JSON.stringify({
isCustom: true,
mediaType: state.customMediaType,
title,
year,
notes: els.customNotes.value.trim() || null,
allSeasons: true,
tmdbId: 0
})
});
els.customForm.reset();
state.customMediaType = "movie";
root.querySelectorAll('[data-role="custom-type"]').forEach((item) => {
item.classList.toggle("active", item.dataset.type === "movie");
});
showMessage(`Custom request submitted for “${title}”.`);
setView("mine");
} catch (error) {
showMessage(error.message, true);
} finally {
els.customSubmit.disabled = false;
}
});
Promise.all([loadStatus(), loadCurrentUser()]).then(() => {
applyAdminUi();
});
return { setView, reload: () => { loadStatus(); loadRequests(); } };
}
function mount(container, options = {}) {
if (!container) {
return null;
}
const force = !!options.force;
const hasUi = !!container.querySelector(".req-root");
if (container.dataset.reqMounted === "1" && hasUi && !force) {
const existing = container._jellyfinRequestController || null;
existing?.reload?.();
return existing;
}
container.innerHTML = MARKUP;
const root = container.querySelector(".req-root");
if (options.embed) {
root.classList.add("req-embed");
}
const controller = createController(root);
container.dataset.reqMounted = "1";
container._jellyfinRequestController = controller;
return controller;
}
window.JellyfinRequestUI = { mount };
const autoRoot = document.getElementById("jellyfin-request-root");
if (autoRoot) {
mount(autoRoot, { embed: autoRoot.dataset.embed === "true" });
}
})();
+2 -35
View File
@@ -6,41 +6,8 @@
<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>
<body class="jellyfin-request-standalone">
<div id="jellyfin-request-root"></div>
<script src="/Requests/Assets/request.js"></script>
</body>
</html>
+4 -6
View File
@@ -24,16 +24,14 @@ https://www.iamparadox.dev/jellyfin/plugins/manifest.json
```
4. From **Catalog**, install **File Transformation**, then install **Request**, then restart Jellyfin.
5. Configure under **Dashboard → Plugins → Request** (TMDB API key + enable submissions).
6. Hard-refresh the browser (Ctrl+F5). You should see a **Request** tab next to Home/Favorites.
Direct page (even without the tab): `/Requests/Page`
5. Configure under **Dashboard → Plugins → Request** (TMDB v3 API key or API Read Access Token + enable submissions).
6. Hard-refresh the browser (Ctrl+F5). You should see a **Request** tab next to Home/Favorites that shows the request UI under the same top bar (no full-page navigation).
## Requirements
- Jellyfin Server **10.11.x**
- .NET SDK **9+** to build from source
- A free [TMDB API key](https://www.themoviedb.org/settings/api)
- A free [TMDB API key or Read Access Token](https://www.themoviedb.org/settings/api) ([docs](https://developer.themoviedb.org/docs/getting-started))
## Build / package a release
@@ -85,7 +83,7 @@ Authenticated Jellyfin users call plugin endpoints under `/Requests`:
| 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.
The TMDB credential stays on the server. Browsers never receive it.
## Data storage
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: "Request"
guid: "11c08950-c4bb-484d-89ff-205b3724416b"
version: "1.0.0.2"
version: "1.0.1.1"
targetAbi: "10.11.11.0"
framework: "net9.0"
overview: "Request movies and TV shows from a local admin review queue"
+5 -5
View File
@@ -9,12 +9,12 @@
"repositoryUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies",
"versions": [
{
"version": "1.0.0.2",
"changelog": "Inject Request tab via File Transformation (Docker/Unraid safe); keep disk patch fallback",
"version": "1.0.1.1",
"changelog": "Reduce Request tab flicker when returning home from collections",
"targetAbi": "10.11.11.0",
"sourceUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main/release/Jellyfin.Plugin.Request_1.0.0.2.zip",
"checksum": "DFD860D8E616B33B7BE31B3CEE462EAB",
"timestamp": "2026-08-02T20:41:46.8916597Z",
"sourceUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main/release/Jellyfin.Plugin.Request_1.0.1.1.zip",
"checksum": "EADA70C2BC7AAD32623E37FDBD85DF44",
"timestamp": "2026-08-03T01:38:28.4011758Z",
"dependencies": []
}
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -1,5 +1,5 @@
param(
[string]$Version = "1.0.0.2",
[string]$Version = "1.0.1.1",
[string]$TargetAbi = "10.11.11.0",
[string]$RepoRawBase = "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main"
)
@@ -17,7 +17,7 @@ $dllPath = Join-Path $root "Jellyfin.Plugin.Request\bin\Release\net9.0\Jellyfin.
$zipPath = Join-Path $releaseDir $zipFileName
$manifestPath = Join-Path $root "manifest.json"
$timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")
$changelog = "Inject Request tab via File Transformation (Docker/Unraid safe); keep disk patch fallback"
$changelog = "Reduce Request tab flicker when returning home from collections"
Write-Host "Building plugin..."
dotnet build (Join-Path $root "Jellyfin.Plugin.Request.sln") -c Release