Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db166bfc02 | ||
|
|
7044023d98 | ||
|
|
2eed62390b | ||
|
|
3957c6ac1d | ||
|
|
97619f1eb5 | ||
|
|
bfa8115fd0 | ||
|
|
e260677dab | ||
|
|
2a1fcf0588 | ||
|
|
0a5ea07838 | ||
|
|
eb20e64c37 |
No files matched your search
@@ -49,3 +49,6 @@ artifacts/
|
|||||||
|
|
||||||
release/stage/
|
release/stage/
|
||||||
|
|
||||||
|
|
||||||
|
release/tmp_*.zip
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project>
|
<Project>
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<Version>1.0.0.2</Version>
|
<Version>1.0.1.1</Version>
|
||||||
<AssemblyVersion>1.0.0.2</AssemblyVersion>
|
<AssemblyVersion>1.0.1.1</AssemblyVersion>
|
||||||
<FileVersion>1.0.0.2</FileVersion>
|
<FileVersion>1.0.1.1</FileVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.ComponentModel.DataAnnotations;
|
|
||||||
|
|
||||||
namespace Jellyfin.Plugin.Request.Api;
|
namespace Jellyfin.Plugin.Request.Api;
|
||||||
|
|
||||||
@@ -11,15 +10,33 @@ public sealed class CreateRequestDto
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the media type (<c>movie</c> or <c>tv</c>).
|
/// Gets or sets the media type (<c>movie</c> or <c>tv</c>).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Required]
|
|
||||||
public string MediaType { get; set; } = string.Empty;
|
public string MediaType { get; set; } = string.Empty;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the TMDB identifier.
|
/// Gets or sets the TMDB identifier. Ignored for custom requests.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Range(1, int.MaxValue)]
|
|
||||||
public int TmdbId { get; set; }
|
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>
|
/// <summary>
|
||||||
/// Gets or sets optional season numbers for TV.
|
/// Gets or sets optional season numbers for TV.
|
||||||
/// Null or empty with <see cref="AllSeasons"/> true requests everything.
|
/// Null or empty with <see cref="AllSeasons"/> true requests everything.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ using System.Threading.Tasks;
|
|||||||
using Jellyfin.Data;
|
using Jellyfin.Data;
|
||||||
using Jellyfin.Database.Implementations.Enums;
|
using Jellyfin.Database.Implementations.Enums;
|
||||||
using Jellyfin.Plugin.Request.Configuration;
|
using Jellyfin.Plugin.Request.Configuration;
|
||||||
|
using Jellyfin.Plugin.Request.Hosting;
|
||||||
using Jellyfin.Plugin.Request.Storage;
|
using Jellyfin.Plugin.Request.Storage;
|
||||||
using Jellyfin.Plugin.Request.Tmdb;
|
using Jellyfin.Plugin.Request.Tmdb;
|
||||||
using MediaBrowser.Controller.Library;
|
using MediaBrowser.Controller.Library;
|
||||||
@@ -60,11 +61,14 @@ public sealed class RequestController : ControllerBase
|
|||||||
public ActionResult<object> Status()
|
public ActionResult<object> Status()
|
||||||
{
|
{
|
||||||
var config = GetConfig();
|
var config = GetConfig();
|
||||||
|
var userId = GetUserId();
|
||||||
return Ok(new
|
return Ok(new
|
||||||
{
|
{
|
||||||
isConfigured = !string.IsNullOrWhiteSpace(config.TmdbApiKey),
|
isConfigured = !string.IsNullOrWhiteSpace(config.TmdbApiKey),
|
||||||
requestSubmissionEnabled = config.EnableRequestSubmission,
|
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");
|
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>
|
/// <summary>
|
||||||
/// Serves plugin web assets.
|
/// Serves plugin web assets.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -203,25 +221,83 @@ public sealed class RequestController : ControllerBase
|
|||||||
/// <returns>Created request.</returns>
|
/// <returns>Created request.</returns>
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public async Task<ActionResult<MediaRequest>> Create(
|
public async Task<ActionResult<MediaRequest>> Create(
|
||||||
[FromBody] CreateRequestDto body,
|
[FromBody] CreateRequestDto? body,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var config = GetConfig();
|
var config = GetConfig();
|
||||||
if (!config.EnableRequestSubmission)
|
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();
|
var userId = GetUserId();
|
||||||
if (userId == Guid.Empty)
|
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);
|
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;
|
var allSeasons = body.AllSeasons;
|
||||||
@@ -267,8 +343,10 @@ public sealed class RequestController : ControllerBase
|
|||||||
Id = Guid.NewGuid(),
|
Id = Guid.NewGuid(),
|
||||||
MediaType = mediaType,
|
MediaType = mediaType,
|
||||||
TmdbId = detail.TmdbId,
|
TmdbId = detail.TmdbId,
|
||||||
|
IsCustom = false,
|
||||||
Title = detail.Title,
|
Title = detail.Title,
|
||||||
Year = detail.Year,
|
Year = detail.Year,
|
||||||
|
Notes = string.IsNullOrWhiteSpace(body.Notes) ? null : body.Notes.Trim(),
|
||||||
PosterPath = detail.PosterPath,
|
PosterPath = detail.PosterPath,
|
||||||
Seasons = seasons,
|
Seasons = seasons,
|
||||||
AllSeasons = mediaType == "tv" && allSeasons,
|
AllSeasons = mediaType == "tv" && allSeasons,
|
||||||
@@ -279,7 +357,7 @@ public sealed class RequestController : ControllerBase
|
|||||||
};
|
};
|
||||||
|
|
||||||
await _store.AddAsync(request, cancellationToken).ConfigureAwait(false);
|
await _store.AddAsync(request, cancellationToken).ConfigureAwait(false);
|
||||||
return CreatedAtAction(nameof(List), new { id = request.Id }, request);
|
return StatusCode(StatusCodes.Status201Created, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -342,19 +420,19 @@ public sealed class RequestController : ControllerBase
|
|||||||
var userId = GetUserId();
|
var userId = GetUserId();
|
||||||
if (userId == Guid.Empty)
|
if (userId == Guid.Empty)
|
||||||
{
|
{
|
||||||
return Unauthorized();
|
return Unauthorized(new { message = "You must be signed in." });
|
||||||
}
|
}
|
||||||
|
|
||||||
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
|
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
|
||||||
if (existing is null)
|
if (existing is null)
|
||||||
{
|
{
|
||||||
return NotFound();
|
return NotFound(new { message = "Request not found." });
|
||||||
}
|
}
|
||||||
|
|
||||||
var isAdmin = IsAdministrator(userId);
|
var isAdmin = IsAdministrator(userId);
|
||||||
if (!isAdmin && (existing.RequestedByUserId != userId || existing.Status != RequestStatus.Pending))
|
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);
|
await _store.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
|
||||||
@@ -370,18 +448,18 @@ public sealed class RequestController : ControllerBase
|
|||||||
var userId = GetUserId();
|
var userId = GetUserId();
|
||||||
if (userId == Guid.Empty)
|
if (userId == Guid.Empty)
|
||||||
{
|
{
|
||||||
return Unauthorized();
|
return Unauthorized(new { message = "You must be signed in." });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!IsAdministrator(userId))
|
if (!IsAdministrator(userId))
|
||||||
{
|
{
|
||||||
return Forbid();
|
return StatusCode(StatusCodes.Status403Forbidden, new { message = "Administrator access is required." });
|
||||||
}
|
}
|
||||||
|
|
||||||
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
|
var existing = await _store.GetByIdAsync(id, cancellationToken).ConfigureAwait(false);
|
||||||
if (existing is null)
|
if (existing is null)
|
||||||
{
|
{
|
||||||
return NotFound();
|
return NotFound(new { message = "Request not found." });
|
||||||
}
|
}
|
||||||
|
|
||||||
existing.Status = status;
|
existing.Status = status;
|
||||||
@@ -405,6 +483,7 @@ public sealed class RequestController : ControllerBase
|
|||||||
foreach (var item in existing)
|
foreach (var item in existing)
|
||||||
{
|
{
|
||||||
if (item.RequestedByUserId != userId
|
if (item.RequestedByUserId != userId
|
||||||
|
|| item.IsCustom
|
||||||
|| !item.MediaType.Equals(mediaType, StringComparison.OrdinalIgnoreCase)
|
|| !item.MediaType.Equals(mediaType, StringComparison.OrdinalIgnoreCase)
|
||||||
|| item.TmdbId != tmdbId
|
|| item.TmdbId != tmdbId
|
||||||
|| item.Status is not (RequestStatus.Pending or RequestStatus.Approved))
|
|| item.Status is not (RequestStatus.Pending or RequestStatus.Approved))
|
||||||
@@ -436,6 +515,35 @@ public sealed class RequestController : ControllerBase
|
|||||||
return false;
|
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()
|
private static PluginConfiguration GetConfig()
|
||||||
{
|
{
|
||||||
return Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
return Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||||
@@ -443,10 +551,26 @@ public sealed class RequestController : ControllerBase
|
|||||||
|
|
||||||
private Guid GetUserId()
|
private Guid GetUserId()
|
||||||
{
|
{
|
||||||
var raw = User.FindFirstValue(ClaimTypes.NameIdentifier)
|
string?[] candidates =
|
||||||
?? User.FindFirstValue("sub")
|
[
|
||||||
?? User.FindFirstValue("Jellyfin-UserId");
|
User.FindFirstValue(ClaimTypes.NameIdentifier),
|
||||||
return Guid.TryParse(raw, out var userId) ? userId : Guid.Empty;
|
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)
|
private bool IsAdministrator(Guid userId)
|
||||||
|
|||||||
@@ -13,10 +13,12 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="verticalSection">
|
<div class="verticalSection">
|
||||||
<div class="inputContainer">
|
<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" />
|
<input is="emby-input" type="password" id="TmdbApiKey" autocomplete="off" />
|
||||||
<div class="fieldDescription">
|
<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>
|
||||||
</div>
|
</div>
|
||||||
<label class="checkboxContainer">
|
<label class="checkboxContainer">
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
namespace Jellyfin.Plugin.Request.Hosting;
|
namespace Jellyfin.Plugin.Request.Hosting;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Payload shape expected by the File Transformation callback.
|
/// Payload shape expected by the File Transformation callback/endpoint.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class IndexHtmlPatchPayload
|
public sealed class IndexHtmlPatchPayload
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the current file contents.
|
/// Gets or sets the current file contents.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[JsonProperty("contents")]
|
||||||
|
[JsonPropertyName("contents")]
|
||||||
public string Contents { get; set; } = string.Empty;
|
public string Contents { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
@@ -18,9 +18,14 @@ namespace Jellyfin.Plugin.Request.Hosting;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class WebNavInjector : IHostedService
|
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 MarkerStart = "<!-- jellyfin-plugin-request-nav-start -->";
|
||||||
private const string MarkerEnd = "<!-- jellyfin-plugin-request-nav-end -->";
|
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 static readonly Guid TransformationId = Guid.Parse("11c08950-c4bb-484d-89ff-205b3724416b");
|
||||||
|
|
||||||
private readonly IServerApplicationPaths _applicationPaths;
|
private readonly IServerApplicationPaths _applicationPaths;
|
||||||
@@ -43,12 +48,14 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
{
|
{
|
||||||
if (TryRegisterFileTransformation())
|
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;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
_logger.LogWarning(
|
_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
|
try
|
||||||
{
|
{
|
||||||
@@ -73,14 +80,25 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// File Transformation callback: injects the nav-loader script tag into index.html contents.
|
/// File Transformation reflection callback.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="payload">Current file contents.</param>
|
/// <param name="payload">Current file contents wrapper.</param>
|
||||||
/// <returns>Transformed HTML.</returns>
|
/// <returns>Transformed HTML.</returns>
|
||||||
public static string InjectNavLoader(IndexHtmlPatchPayload payload)
|
public static string InjectNavLoader(JObject payload)
|
||||||
{
|
{
|
||||||
var html = payload?.Contents ?? string.Empty;
|
var html = payload?["contents"]?.ToString() ?? string.Empty;
|
||||||
if (html.Contains(LoaderSrc, StringComparison.Ordinal)
|
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))
|
|| html.Contains(MarkerStart, StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
return html;
|
return html;
|
||||||
@@ -95,11 +113,12 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
|
|
||||||
private async Task RetryRegisterAsync(CancellationToken cancellationToken)
|
private async Task RetryRegisterAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
for (var attempt = 1; attempt <= 10; attempt++)
|
for (var attempt = 1; attempt <= 12; attempt++)
|
||||||
{
|
{
|
||||||
try
|
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)
|
catch (OperationCanceledException)
|
||||||
{
|
{
|
||||||
@@ -116,7 +135,7 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
}
|
}
|
||||||
|
|
||||||
_logger.LogWarning(
|
_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()
|
private bool TryRegisterFileTransformation()
|
||||||
@@ -125,27 +144,33 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
{
|
{
|
||||||
Assembly? fileTransformationAssembly = AssemblyLoadContext.All
|
Assembly? fileTransformationAssembly = AssemblyLoadContext.All
|
||||||
.SelectMany(context => context.Assemblies)
|
.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)
|
if (fileTransformationAssembly is null)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Type? pluginInterfaceType = fileTransformationAssembly.GetType("Jellyfin.Plugin.FileTransformation.PluginInterface");
|
Type? pluginInterfaceType = fileTransformationAssembly.GetType(
|
||||||
|
"Jellyfin.Plugin.FileTransformation.PluginInterface");
|
||||||
MethodInfo? registerMethod = pluginInterfaceType?.GetMethod(
|
MethodInfo? registerMethod = pluginInterfaceType?.GetMethod(
|
||||||
"RegisterTransformation",
|
"RegisterTransformation",
|
||||||
BindingFlags.Public | BindingFlags.Static);
|
BindingFlags.Public | BindingFlags.Static);
|
||||||
|
|
||||||
if (registerMethod is null)
|
if (registerMethod is null)
|
||||||
{
|
{
|
||||||
|
_logger.LogWarning("File Transformation PluginInterface.RegisterTransformation was not found.");
|
||||||
return false;
|
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()
|
JObject payload = new()
|
||||||
{
|
{
|
||||||
["id"] = TransformationId,
|
["id"] = TransformationId,
|
||||||
["fileNamePattern"] = @"index\.html",
|
["fileNamePattern"] = @"index\.html",
|
||||||
|
["transformationEndpoint"] = TransformationEndpoint,
|
||||||
["callbackAssembly"] = typeof(WebNavInjector).Assembly.FullName,
|
["callbackAssembly"] = typeof(WebNavInjector).Assembly.FullName,
|
||||||
["callbackClass"] = typeof(WebNavInjector).FullName,
|
["callbackClass"] = typeof(WebNavInjector).FullName,
|
||||||
["callbackMethod"] = nameof(InjectNavLoader)
|
["callbackMethod"] = nameof(InjectNavLoader)
|
||||||
@@ -156,7 +181,7 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogDebug(ex, "File Transformation registration failed.");
|
_logger.LogWarning(ex, "File Transformation registration failed.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -171,14 +196,13 @@ public sealed class WebNavInjector : IHostedService
|
|||||||
}
|
}
|
||||||
|
|
||||||
var html = File.ReadAllText(indexPath);
|
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);
|
_logger.LogInformation("Request nav loader already present in {Path}", indexPath);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var updated = InjectNavLoader(new IndexHtmlPatchPayload { Contents = html });
|
File.WriteAllText(indexPath, InjectHtml(html));
|
||||||
File.WriteAllText(indexPath, updated);
|
|
||||||
_logger.LogInformation("Injected Request nav loader into {Path}", indexPath);
|
_logger.LogInformation("Injected Request nav loader into {Path}", indexPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,15 +19,25 @@ public sealed class MediaRequest
|
|||||||
public string MediaType { get; set; } = string.Empty;
|
public string MediaType { get; set; } = string.Empty;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the TMDB identifier.
|
/// Gets or sets the TMDB identifier. Zero for custom titles not found on TMDB.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int TmdbId { get; set; }
|
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>
|
/// <summary>
|
||||||
/// Gets or sets the display title.
|
/// Gets or sets the display title.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Title { get; set; } = string.Empty;
|
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>
|
/// <summary>
|
||||||
/// Gets or sets the release year when known.
|
/// Gets or sets the release year when known.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ using System.Collections.Generic;
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Headers;
|
||||||
|
using System.Text.Json;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
@@ -19,6 +20,11 @@ public sealed class TmdbClient
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public const string HttpClientName = "Tmdb";
|
public const string HttpClientName = "Tmdb";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||||
|
{
|
||||||
|
PropertyNameCaseInsensitive = true
|
||||||
|
};
|
||||||
|
|
||||||
private readonly IHttpClientFactory _httpClientFactory;
|
private readonly IHttpClientFactory _httpClientFactory;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -42,7 +48,6 @@ public sealed class TmdbClient
|
|||||||
string mediaType,
|
string mediaType,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var apiKey = RequireApiKey();
|
|
||||||
var path = mediaType switch
|
var path = mediaType switch
|
||||||
{
|
{
|
||||||
"movie" => "search/movie",
|
"movie" => "search/movie",
|
||||||
@@ -50,9 +55,9 @@ public sealed class TmdbClient
|
|||||||
_ => "search/multi"
|
_ => "search/multi"
|
||||||
};
|
};
|
||||||
|
|
||||||
var url = $"{path}?api_key={Uri.EscapeDataString(apiKey)}&query={Uri.EscapeDataString(query)}&include_adult=false";
|
var relativeUrl =
|
||||||
var client = _httpClientFactory.CreateClient(HttpClientName);
|
$"{path}?query={Uri.EscapeDataString(query)}&include_adult=false&language=en-US&page=1";
|
||||||
var response = await client.GetFromJsonAsync<TmdbSearchResponse>(url, cancellationToken).ConfigureAwait(false);
|
var response = await GetAsync<TmdbSearchResponse>(relativeUrl, cancellationToken).ConfigureAwait(false);
|
||||||
if (response?.Results is null)
|
if (response?.Results is null)
|
||||||
{
|
{
|
||||||
return [];
|
return [];
|
||||||
@@ -78,13 +83,10 @@ public sealed class TmdbClient
|
|||||||
int tmdbId,
|
int tmdbId,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var apiKey = RequireApiKey();
|
|
||||||
var client = _httpClientFactory.CreateClient(HttpClientName);
|
|
||||||
|
|
||||||
if (mediaType.Equals("movie", StringComparison.OrdinalIgnoreCase))
|
if (mediaType.Equals("movie", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
var movie = await client.GetFromJsonAsync<TmdbMovieDetailResponse>(
|
var movie = await GetAsync<TmdbMovieDetailResponse>(
|
||||||
$"movie/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
|
$"movie/{tmdbId}?language=en-US",
|
||||||
cancellationToken)
|
cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
if (movie is null)
|
if (movie is null)
|
||||||
@@ -105,8 +107,8 @@ public sealed class TmdbClient
|
|||||||
|
|
||||||
if (mediaType.Equals("tv", StringComparison.OrdinalIgnoreCase))
|
if (mediaType.Equals("tv", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
var show = await client.GetFromJsonAsync<TmdbTvDetailResponse>(
|
var show = await GetAsync<TmdbTvDetailResponse>(
|
||||||
$"tv/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
|
$"tv/{tmdbId}?language=en-US",
|
||||||
cancellationToken)
|
cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
if (show is null)
|
if (show is null)
|
||||||
@@ -137,15 +139,76 @@ public sealed class TmdbClient
|
|||||||
throw new ArgumentException("mediaType must be movie or tv.", nameof(mediaType));
|
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;
|
var credential = RequireCredential();
|
||||||
if (string.IsNullOrWhiteSpace(apiKey))
|
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.");
|
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)
|
private static TmdbSearchItem? MapSearchResult(TmdbRawResult result, string requestedType)
|
||||||
@@ -159,7 +222,9 @@ public sealed class TmdbClient
|
|||||||
return null;
|
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))
|
if (string.IsNullOrWhiteSpace(title))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
@@ -187,4 +252,6 @@ public sealed class TmdbClient
|
|||||||
? year
|
? year
|
||||||
: null;
|
: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private readonly record struct TmdbCredential(string Value, bool UseBearer);
|
||||||
}
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
(() => {
|
(() => {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const REQUEST_URL = "/Requests/Page";
|
const TAB_ATTR = "data-jellyfin-request-tab";
|
||||||
const STYLE_ID = "jellyfin-plugin-request-nav-style";
|
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) {
|
let ensuring = null;
|
||||||
return [
|
let assetsPromise = null;
|
||||||
node?.textContent,
|
let guardAttached = false;
|
||||||
node?.getAttribute?.("aria-label"),
|
let cachedButton = null;
|
||||||
node?.getAttribute?.("title"),
|
let cachedPanel = null;
|
||||||
node?.getAttribute?.("data-title")
|
let headerObserver = null;
|
||||||
].filter(Boolean).join(" ").replace(/\s+/g, " ").trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensureStyle() {
|
function ensureStyle() {
|
||||||
if (document.getElementById(STYLE_ID)) {
|
if (document.getElementById(STYLE_ID)) {
|
||||||
@@ -20,37 +20,314 @@
|
|||||||
|
|
||||||
const style = document.createElement("style");
|
const style = document.createElement("style");
|
||||||
style.id = STYLE_ID;
|
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);
|
document.head.appendChild(style);
|
||||||
}
|
}
|
||||||
|
|
||||||
function controlsIn(container) {
|
function isHomeTabContext() {
|
||||||
return Array.from(container.querySelectorAll("a, button, [role='button'], [role='menuitem'], [role='link']"));
|
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) {
|
const page = document.getElementById("indexPage");
|
||||||
event.preventDefault();
|
if (!page || page.classList.contains("hide")) {
|
||||||
event.stopPropagation();
|
return false;
|
||||||
event.stopImmediatePropagation?.();
|
|
||||||
window.location.assign(REQUEST_URL);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function wireLink(link) {
|
const visiblePage = document.querySelector(".page:not(.hide)");
|
||||||
link.href = REQUEST_URL;
|
return !visiblePage || visiblePage.id === "indexPage";
|
||||||
link.addEventListener("click", openRequestPage, true);
|
|
||||||
return link;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function labelMatches(node, labels) {
|
function loadAssets() {
|
||||||
const label = textOf(node);
|
if (assetsPromise) {
|
||||||
return labels.some((value) => label === value || label.includes(value));
|
return assetsPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isDrawerElement(node) {
|
assetsPromise = new Promise((resolve, reject) => {
|
||||||
return Boolean(node?.closest?.(".mainDrawer,.mainDrawer-scrollContainer,.drawerContent,.MuiDrawer-paper"));
|
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 = [
|
const selectors = [
|
||||||
".mainDrawer-scrollContainer",
|
".mainDrawer-scrollContainer",
|
||||||
".mainDrawer .scrollContainer",
|
".mainDrawer .scrollContainer",
|
||||||
@@ -58,168 +335,37 @@
|
|||||||
".navMenu",
|
".navMenu",
|
||||||
".MuiDrawer-paper"
|
".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 selector of selectors) {
|
||||||
for (const candidate of document.querySelectorAll(selector)) {
|
for (const container 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")) {
|
if (container.querySelector(".jf-request-menu-item")) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const controls = controlsIn(container);
|
const controls = Array.from(container.querySelectorAll("a, button, [role='button'], [role='menuitem']"));
|
||||||
const after = controls.find((item) => /^(favorites|favourites)$/i.test(textOf(item)))
|
const labels = controls.map((node) => (node.textContent || "").trim().toLowerCase());
|
||||||
|| controls.find((item) => /^home$/i.test(textOf(item)) || textOf(item).includes("home"))
|
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];
|
|| controls[0];
|
||||||
if (!after) {
|
if (!after) {
|
||||||
continue;
|
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) {
|
if (after.parentElement === container) {
|
||||||
after.insertAdjacentElement("afterend", link);
|
after.insertAdjacentElement("afterend", link);
|
||||||
} else {
|
} else {
|
||||||
@@ -227,13 +373,131 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function insertEntries() {
|
|
||||||
insertTopTab();
|
|
||||||
insertSideMenuItem();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
insertEntries();
|
function ensureRequestTab() {
|
||||||
setInterval(insertEntries, 1000);
|
if (ensuring) {
|
||||||
new MutationObserver(insertEntries).observe(document.documentElement, { childList: true, subtree: true });
|
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();
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
@@ -10,21 +10,32 @@
|
|||||||
--req-warn: #f0ad4e;
|
--req-warn: #f0ad4e;
|
||||||
}
|
}
|
||||||
|
|
||||||
* {
|
.req-root,
|
||||||
|
.req-root * {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
html,
|
body.jellyfin-request-standalone {
|
||||||
body {
|
|
||||||
margin: 0;
|
margin: 0;
|
||||||
min-height: 100%;
|
min-height: 100%;
|
||||||
|
padding: 1.25rem;
|
||||||
background: var(--req-bg);
|
background: var(--req-bg);
|
||||||
color: var(--req-text);
|
color: var(--req-text);
|
||||||
font-family: Inherit, "Segoe UI", Roboto, sans-serif;
|
font-family: Inherit, "Segoe UI", Roboto, sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
.req-root {
|
||||||
padding: 1.25rem;
|
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 {
|
.req-header {
|
||||||
@@ -82,7 +93,21 @@ body {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: 0.75rem;
|
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"] {
|
.req-search-row input[type="search"] {
|
||||||
@@ -230,6 +255,41 @@ body {
|
|||||||
.req-badge.approved { background: #0f3d1f; color: #8dffb0; }
|
.req-badge.approved { background: #0f3d1f; color: #8dffb0; }
|
||||||
.req-badge.rejected { background: #4a1212; color: #ff9d9d; }
|
.req-badge.rejected { background: #4a1212; color: #ff9d9d; }
|
||||||
.req-badge.fulfilled { background: #0a3345; color: #8ad7ff; }
|
.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 {
|
.req-list-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -1,32 +1,90 @@
|
|||||||
(() => {
|
(() => {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const API = "/Requests";
|
function apiRoot() {
|
||||||
const state = {
|
try {
|
||||||
mediaType: "multi",
|
if (typeof ApiClient !== "undefined" && typeof ApiClient.serverAddress === "function") {
|
||||||
status: null,
|
const base = String(ApiClient.serverAddress() || "").replace(/\/+$/, "");
|
||||||
isAdmin: false,
|
if (base) {
|
||||||
detail: null,
|
return `${base}/Requests`;
|
||||||
requests: []
|
}
|
||||||
};
|
}
|
||||||
|
} catch {
|
||||||
|
// Fall through.
|
||||||
|
}
|
||||||
|
|
||||||
const els = {
|
return "/Requests";
|
||||||
statusBanner: document.getElementById("statusBanner"),
|
}
|
||||||
globalMessage: document.getElementById("globalMessage"),
|
|
||||||
searchInput: document.getElementById("searchInput"),
|
const MARKUP = `
|
||||||
searchBtn: document.getElementById("searchBtn"),
|
<div class="req-root">
|
||||||
results: document.getElementById("results"),
|
<header class="req-header">
|
||||||
detail: document.getElementById("detail"),
|
<h1 class="req-title">Request</h1>
|
||||||
mineList: document.getElementById("mineList"),
|
<nav class="req-tabs" aria-label="Request views">
|
||||||
adminList: document.getElementById("adminList"),
|
<button type="button" class="req-tab active" data-view="search">Search</button>
|
||||||
adminTab: document.getElementById("adminTab"),
|
<button type="button" class="req-tab" data-view="custom">Custom</button>
|
||||||
searchView: document.getElementById("searchView"),
|
<button type="button" class="req-tab" data-view="mine">My requests</button>
|
||||||
mineView: document.getElementById("mineView"),
|
<button type="button" class="req-tab req-hidden" data-view="admin" data-role="admin-tab">Admin queue</button>
|
||||||
adminView: document.getElementById("adminView")
|
</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() {
|
function authHeader() {
|
||||||
try {
|
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 raw = localStorage.getItem("jellyfin_credentials");
|
||||||
const credentials = raw ? JSON.parse(raw) : null;
|
const credentials = raw ? JSON.parse(raw) : null;
|
||||||
const server = credentials?.Servers?.find((item) => item.AccessToken) || credentials?.Servers?.[0];
|
const server = credentials?.Servers?.find((item) => item.AccessToken) || credentials?.Servers?.[0];
|
||||||
@@ -47,14 +105,30 @@
|
|||||||
async function errorMessage(response) {
|
async function errorMessage(response) {
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
try {
|
try {
|
||||||
return JSON.parse(text).message || `${response.status} ${response.statusText}`;
|
const data = JSON.parse(text);
|
||||||
} catch {
|
if (data.message) {
|
||||||
return text || `${response.status} ${response.statusText}`;
|
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 = {}) {
|
async function api(path, options = {}) {
|
||||||
const response = await fetch(`${API}${path}`, {
|
const response = await fetch(`${apiRoot()}${path}`, {
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
@@ -75,28 +149,72 @@
|
|||||||
return text ? JSON.parse(text) : null;
|
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) {
|
function posterUrl(path, width) {
|
||||||
return path ? `https://image.tmdb.org/t/p/w${width || 342}${path}` : "";
|
return path ? `https://image.tmdb.org/t/p/w${width || 342}${path}` : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function statusName(value) {
|
function statusName(value) {
|
||||||
if (typeof value === "string") {
|
if (typeof value === "string" && value) {
|
||||||
return 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) {
|
function statusClass(value) {
|
||||||
return statusName(value).toLowerCase();
|
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) {
|
function escapeHtml(value) {
|
||||||
return String(value ?? "")
|
return String(value ?? "")
|
||||||
.replaceAll("&", "&")
|
.replaceAll("&", "&")
|
||||||
@@ -105,14 +223,68 @@
|
|||||||
.replaceAll('"', """);
|
.replaceAll('"', """);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
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);
|
tab.classList.toggle("active", tab.dataset.view === view);
|
||||||
});
|
});
|
||||||
els.searchView.classList.toggle("req-hidden", view !== "search");
|
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.mineView.classList.toggle("req-hidden", view !== "mine");
|
||||||
els.adminView.classList.toggle("req-hidden", view !== "admin");
|
els.adminView.classList.toggle("req-hidden", view !== "admin");
|
||||||
if (view === "mine" || view === "admin") {
|
if (view === "mine" || (view === "admin" && state.isAdmin)) {
|
||||||
loadRequests();
|
loadRequests();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -120,10 +292,15 @@
|
|||||||
async function loadStatus() {
|
async function loadStatus() {
|
||||||
try {
|
try {
|
||||||
state.status = await api("/Status");
|
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.textContent = "TMDB is not configured. An administrator must set a TMDB API key in Dashboard → Plugins → Request.";
|
||||||
els.statusBanner.classList.remove("req-hidden");
|
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.textContent = "Search is available. Request submission is disabled by the administrator.";
|
||||||
els.statusBanner.classList.remove("req-hidden");
|
els.statusBanner.classList.remove("req-hidden");
|
||||||
} else {
|
} else {
|
||||||
@@ -136,7 +313,12 @@
|
|||||||
|
|
||||||
async function loadCurrentUser() {
|
async function loadCurrentUser() {
|
||||||
try {
|
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",
|
cache: "no-store",
|
||||||
headers: authHeader()
|
headers: authHeader()
|
||||||
});
|
});
|
||||||
@@ -144,42 +326,84 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const me = await response.json();
|
me = await response.json();
|
||||||
state.isAdmin = !!me?.Policy?.IsAdministrator;
|
|
||||||
els.adminTab.classList.toggle("req-hidden", !state.isAdmin);
|
|
||||||
} catch {
|
|
||||||
// Non-fatal: admin tab stays hidden.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
async function runSearch() {
|
||||||
const query = els.searchInput.value.trim();
|
const query = els.searchInput.value.trim();
|
||||||
if (!query) {
|
if (!query) {
|
||||||
showMessage("Enter a search query.", true);
|
showMessage("Enter a search query.", true);
|
||||||
|
setSearchMeta("");
|
||||||
return;
|
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.detail.classList.add("req-hidden");
|
||||||
|
els.results.classList.remove("req-hidden");
|
||||||
|
els.results.innerHTML = "";
|
||||||
try {
|
try {
|
||||||
const results = await api(`/Search?query=${encodeURIComponent(query)}&type=${encodeURIComponent(state.mediaType)}`);
|
const results = await api(`/Search?query=${encodeURIComponent(query)}&type=${encodeURIComponent(state.mediaType)}`);
|
||||||
showMessage(results.length ? "" : "No results found.");
|
const list = Array.isArray(results) ? results : [];
|
||||||
renderResults(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) {
|
} catch (error) {
|
||||||
|
setSearchMeta(`Search failed for “${query}”`);
|
||||||
showMessage(error.message, true);
|
showMessage(error.message, true);
|
||||||
els.results.innerHTML = "";
|
els.results.innerHTML = "";
|
||||||
|
} finally {
|
||||||
|
els.searchBtn.disabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderResults(results) {
|
function renderResults(results) {
|
||||||
|
if (!results.length) {
|
||||||
|
els.results.innerHTML = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
els.results.innerHTML = results.map((item) => {
|
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 `
|
return `
|
||||||
<article class="req-card" data-type="${escapeHtml(item.mediaType)}" data-id="${item.tmdbId}">
|
<article class="req-card" data-type="${escapeHtml(mediaType)}" data-id="${escapeHtml(tmdbId)}">
|
||||||
${img ? `<img src="${escapeHtml(img)}" alt="" loading="lazy" />` : `<div class="req-card-body"><p class="req-muted">No poster</p></div>`}
|
${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">
|
<div class="req-card-body">
|
||||||
<p class="req-card-title">${escapeHtml(item.title)}</p>
|
<p class="req-card-title">${escapeHtml(title)}</p>
|
||||||
<p class="req-muted">${escapeHtml(item.mediaType)}${item.year ? ` · ${item.year}` : ""}</p>
|
<p class="req-muted">${escapeHtml(mediaType)}${year ? ` · ${escapeHtml(year)}` : ""}</p>
|
||||||
</div>
|
</div>
|
||||||
</article>`;
|
</article>`;
|
||||||
}).join("");
|
}).join("");
|
||||||
@@ -202,18 +426,28 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderDetail(detail) {
|
function renderDetail(detail) {
|
||||||
const img = detail.posterUrl || posterUrl(detail.posterPath, 500);
|
const mediaType = detail.mediaType || detail.MediaType || "";
|
||||||
const allowSeasons = state.status?.allowSeasonSelection !== false && detail.mediaType === "tv";
|
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
|
const seasonHtml = allowSeasons
|
||||||
? `<div class="req-seasons">
|
? `<div class="req-seasons">
|
||||||
<label class="req-season"><input type="checkbox" id="allSeasons" checked /> All seasons</label>
|
<label class="req-season"><input type="checkbox" data-role="all-seasons" checked /> All seasons</label>
|
||||||
${detail.seasons.map((season) => `
|
${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">
|
<label class="req-season">
|
||||||
<input type="checkbox" class="season-box" value="${season.seasonNumber}" disabled />
|
<input type="checkbox" class="season-box" value="${escapeHtml(seasonNumber)}" disabled />
|
||||||
${escapeHtml(season.name)} <span class="req-muted">(${season.episodeCount})</span>
|
${escapeHtml(seasonName)} <span class="req-muted">(${escapeHtml(episodeCount)})</span>
|
||||||
</label>`).join("")}
|
</label>`;
|
||||||
|
}).join("")}
|
||||||
</div>`
|
</div>`
|
||||||
: detail.mediaType === "tv"
|
: mediaType === "tv"
|
||||||
? `<p class="req-muted">This request will cover all seasons.</p>`
|
? `<p class="req-muted">This request will cover all seasons.</p>`
|
||||||
: "";
|
: "";
|
||||||
|
|
||||||
@@ -221,28 +455,28 @@
|
|||||||
els.detail.innerHTML = `
|
els.detail.innerHTML = `
|
||||||
${img ? `<img class="req-detail-poster" src="${escapeHtml(img)}" alt="" />` : "<div></div>"}
|
${img ? `<img class="req-detail-poster" src="${escapeHtml(img)}" alt="" />` : "<div></div>"}
|
||||||
<div class="req-detail-meta">
|
<div class="req-detail-meta">
|
||||||
<button type="button" class="req-btn" id="backToResults">Back to results</button>
|
<button type="button" class="req-btn" data-role="back-results">Back to results</button>
|
||||||
<h2 class="req-detail-title">${escapeHtml(detail.title)}</h2>
|
<h2 class="req-detail-title">${escapeHtml(title)}</h2>
|
||||||
<p class="req-muted">${escapeHtml(detail.mediaType)}${detail.year ? ` · ${detail.year}` : ""}</p>
|
<p class="req-muted">${escapeHtml(mediaType)}${year ? ` · ${escapeHtml(year)}` : ""}</p>
|
||||||
<p>${escapeHtml(detail.overview || "No overview available.")}</p>
|
<p>${escapeHtml(overview)}</p>
|
||||||
${seasonHtml}
|
${seasonHtml}
|
||||||
<div class="req-detail-actions">
|
<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
|
Request
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>`;
|
</div>`;
|
||||||
|
|
||||||
els.results.classList.add("req-hidden");
|
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.detail.classList.add("req-hidden");
|
||||||
els.results.classList.remove("req-hidden");
|
els.results.classList.remove("req-hidden");
|
||||||
});
|
});
|
||||||
|
|
||||||
const allSeasons = document.getElementById("allSeasons");
|
const allSeasons = els.detail.querySelector('[data-role="all-seasons"]');
|
||||||
if (allSeasons) {
|
if (allSeasons) {
|
||||||
allSeasons.addEventListener("change", () => {
|
allSeasons.addEventListener("change", () => {
|
||||||
document.querySelectorAll(".season-box").forEach((box) => {
|
els.detail.querySelectorAll(".season-box").forEach((box) => {
|
||||||
box.disabled = allSeasons.checked;
|
box.disabled = allSeasons.checked;
|
||||||
if (allSeasons.checked) {
|
if (allSeasons.checked) {
|
||||||
box.checked = false;
|
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) {
|
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 = {
|
const payload = {
|
||||||
mediaType: detail.mediaType,
|
mediaType,
|
||||||
tmdbId: detail.tmdbId,
|
tmdbId,
|
||||||
allSeasons: true,
|
allSeasons: true,
|
||||||
seasons: null
|
seasons: null
|
||||||
};
|
};
|
||||||
|
|
||||||
const allSeasons = document.getElementById("allSeasons");
|
const allSeasons = els.detail.querySelector('[data-role="all-seasons"]');
|
||||||
if (detail.mediaType === "tv" && allSeasons && !allSeasons.checked) {
|
if (mediaType === "tv" && allSeasons && !allSeasons.checked) {
|
||||||
const selected = Array.from(document.querySelectorAll(".season-box:checked")).map((box) => Number(box.value));
|
const selected = Array.from(els.detail.querySelectorAll(".season-box:checked")).map((box) => Number(box.value));
|
||||||
if (!selected.length) {
|
if (!selected.length) {
|
||||||
showMessage("Select at least one season, or choose all seasons.", true);
|
showMessage("Select at least one season, or choose all seasons.", true);
|
||||||
return;
|
return;
|
||||||
@@ -276,7 +524,7 @@
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await api("", { method: "POST", body: JSON.stringify(payload) });
|
await api("", { method: "POST", body: JSON.stringify(payload) });
|
||||||
showMessage(`Requested “${detail.title}”.`);
|
showMessage(`Requested “${title}”.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showMessage(error.message, true);
|
showMessage(error.message, true);
|
||||||
}
|
}
|
||||||
@@ -284,13 +532,16 @@
|
|||||||
|
|
||||||
async function loadRequests() {
|
async function loadRequests() {
|
||||||
try {
|
try {
|
||||||
state.requests = await api("");
|
const raw = await api("");
|
||||||
|
state.requests = (Array.isArray(raw) ? raw : []).map(normalizeRequest);
|
||||||
renderRequestList(els.mineList, state.requests, false);
|
renderRequestList(els.mineList, state.requests, false);
|
||||||
if (state.isAdmin) {
|
if (state.isAdmin) {
|
||||||
const pendingFirst = [...state.requests].sort((a, b) => {
|
const pendingFirst = [...state.requests].sort((a, b) => {
|
||||||
const aPending = statusName(a.status) === "Pending" ? 0 : 1;
|
const aPending = statusName(a.status) === "Pending" ? 0 : 1;
|
||||||
const bPending = statusName(b.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);
|
renderRequestList(els.adminList, pendingFirst, true);
|
||||||
}
|
}
|
||||||
@@ -300,36 +551,42 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderRequestList(container, items, adminMode) {
|
function renderRequestList(container, items, adminMode) {
|
||||||
|
const showAdminActions = !!(adminMode && state.isAdmin);
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
container.innerHTML = `<p class="req-message">No requests yet.</p>`;
|
container.innerHTML = `<p class="req-message">No requests yet.</p>`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
container.innerHTML = items.map((item) => {
|
container.innerHTML = items.map((raw) => {
|
||||||
|
const item = normalizeRequest(raw);
|
||||||
const img = posterUrl(item.posterPath, 185);
|
const img = posterUrl(item.posterPath, 185);
|
||||||
const seasons = item.allSeasons
|
const seasons = item.allSeasons
|
||||||
? "All seasons"
|
? "All seasons"
|
||||||
: (item.seasons || []).length
|
: item.seasons.length
|
||||||
? `Seasons ${(item.seasons || []).join(", ")}`
|
? `Seasons ${item.seasons.join(", ")}`
|
||||||
: "";
|
: "";
|
||||||
const actions = adminMode
|
const status = statusName(item.status);
|
||||||
? `
|
const requestId = String(item.id || "");
|
||||||
<button type="button" class="req-btn" data-action="approve" data-id="${item.id}">Approve</button>
|
let actions = "";
|
||||||
<button type="button" class="req-btn" data-action="reject" data-id="${item.id}">Reject</button>
|
if (showAdminActions && requestId) {
|
||||||
<button type="button" class="req-btn" data-action="fulfill" data-id="${item.id}">Fulfilled</button>
|
actions = `
|
||||||
<button type="button" class="req-btn danger" data-action="delete" data-id="${item.id}">Delete</button>`
|
<button type="button" class="req-btn" data-action="approve" data-id="${escapeHtml(requestId)}">Approve</button>
|
||||||
: (statusName(item.status) === "Pending"
|
<button type="button" class="req-btn" data-action="reject" data-id="${escapeHtml(requestId)}">Reject</button>
|
||||||
? `<button type="button" class="req-btn danger" data-action="delete" data-id="${item.id}">Cancel</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 `
|
return `
|
||||||
<article class="req-list-item">
|
<article class="req-list-item">
|
||||||
${img ? `<img src="${escapeHtml(img)}" alt="" />` : "<div></div>"}
|
${img ? `<img src="${escapeHtml(img)}" alt="" />` : "<div></div>"}
|
||||||
<div>
|
<div>
|
||||||
<p class="req-card-title">${escapeHtml(item.title)}</p>
|
<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 ? ` · ${item.year}` : ""}${seasons ? ` · ${escapeHtml(seasons)}` : ""}</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)} · ${new Date(item.createdAtUtc).toLocaleString()}</p>
|
<p class="req-muted">Requested by ${escapeHtml(item.requestedByName)} · ${escapeHtml(formatRequestDate(item.createdAtUtc))}</p>
|
||||||
<span class="req-badge ${statusClass(item.status)}">${escapeHtml(statusName(item.status))}</span>
|
<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>` : ""}
|
${item.adminNote ? `<p class="req-muted">${escapeHtml(item.adminNote)}</p>` : ""}
|
||||||
</div>
|
</div>
|
||||||
<div class="req-list-actions">${actions}</div>
|
<div class="req-list-actions">${actions}</div>
|
||||||
@@ -337,37 +594,74 @@
|
|||||||
}).join("");
|
}).join("");
|
||||||
|
|
||||||
container.querySelectorAll("[data-action]").forEach((button) => {
|
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 {
|
try {
|
||||||
if (action === "delete") {
|
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 {
|
} else {
|
||||||
await api(`/${id}/${action}`, { method: "POST", body: "{}" });
|
showMessage("Unknown action.", true);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await loadRequests();
|
await loadRequests();
|
||||||
showMessage("Updated.");
|
showMessage(messages[action] || "Updated.");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showMessage(error.message, true);
|
showMessage(error.message, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.querySelectorAll(".req-tab").forEach((tab) => {
|
root.querySelectorAll(".req-tab").forEach((tab) => {
|
||||||
tab.addEventListener("click", () => setView(tab.dataset.view));
|
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", () => {
|
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");
|
button.classList.add("active");
|
||||||
state.mediaType = button.dataset.type;
|
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.searchBtn.addEventListener("click", runSearch);
|
||||||
els.searchInput.addEventListener("keydown", (event) => {
|
els.searchInput.addEventListener("keydown", (event) => {
|
||||||
if (event.key === "Enter") {
|
if (event.key === "Enter") {
|
||||||
@@ -375,6 +669,90 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
loadStatus();
|
els.customForm.addEventListener("submit", async (event) => {
|
||||||
loadCurrentUser();
|
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" });
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
@@ -6,41 +6,8 @@
|
|||||||
<title>Request</title>
|
<title>Request</title>
|
||||||
<link rel="stylesheet" href="/Requests/Assets/request.css" />
|
<link rel="stylesheet" href="/Requests/Assets/request.css" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body class="jellyfin-request-standalone">
|
||||||
<header class="req-header">
|
<div id="jellyfin-request-root"></div>
|
||||||
<h1 class="req-title">Request</h1>
|
|
||||||
<nav class="req-tabs" aria-label="Request views">
|
|
||||||
<button type="button" class="req-tab active" data-view="search">Search</button>
|
|
||||||
<button type="button" class="req-tab" data-view="mine">My requests</button>
|
|
||||||
<button type="button" class="req-tab req-hidden" data-view="admin" id="adminTab">Admin queue</button>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<div id="statusBanner" class="req-status-banner req-hidden"></div>
|
|
||||||
<p id="globalMessage" class="req-message req-hidden"></p>
|
|
||||||
|
|
||||||
<section id="searchView">
|
|
||||||
<div class="req-search-row">
|
|
||||||
<input id="searchInput" type="search" placeholder="Search movies or TV shows" autocomplete="off" />
|
|
||||||
<div class="req-type-toggle" role="group" aria-label="Media type">
|
|
||||||
<button type="button" class="req-type-btn active" data-type="multi">All</button>
|
|
||||||
<button type="button" class="req-type-btn" data-type="movie">Movies</button>
|
|
||||||
<button type="button" class="req-type-btn" data-type="tv">TV</button>
|
|
||||||
</div>
|
|
||||||
<button type="button" class="req-btn primary" id="searchBtn">Search</button>
|
|
||||||
</div>
|
|
||||||
<div id="results" class="req-grid"></div>
|
|
||||||
<div id="detail" class="req-detail req-hidden"></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="mineView" class="req-hidden">
|
|
||||||
<div id="mineList" class="req-list"></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="adminView" class="req-hidden">
|
|
||||||
<div id="adminList" class="req-list"></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<script src="/Requests/Assets/request.js"></script>
|
<script src="/Requests/Assets/request.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -24,16 +24,14 @@ https://www.iamparadox.dev/jellyfin/plugins/manifest.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
4. From **Catalog**, install **File Transformation**, then install **Request**, then restart Jellyfin.
|
4. From **Catalog**, install **File Transformation**, then install **Request**, then restart Jellyfin.
|
||||||
5. Configure under **Dashboard → Plugins → Request** (TMDB API key + enable submissions).
|
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.
|
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).
|
||||||
|
|
||||||
Direct page (even without the tab): `/Requests/Page`
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Jellyfin Server **10.11.x**
|
- Jellyfin Server **10.11.x**
|
||||||
- .NET SDK **9+** to build from source
|
- .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
|
## Build / package a release
|
||||||
|
|
||||||
@@ -85,7 +83,7 @@ Authenticated Jellyfin users call plugin endpoints under `/Requests`:
|
|||||||
| POST | `/Requests/{id}/fulfill` | Admin |
|
| POST | `/Requests/{id}/fulfill` | Admin |
|
||||||
| DELETE | `/Requests/{id}` | Admin, or owner while Pending |
|
| 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
|
## Data storage
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: "Request"
|
name: "Request"
|
||||||
guid: "11c08950-c4bb-484d-89ff-205b3724416b"
|
guid: "11c08950-c4bb-484d-89ff-205b3724416b"
|
||||||
version: "1.0.0.2"
|
version: "1.0.1.1"
|
||||||
targetAbi: "10.11.11.0"
|
targetAbi: "10.11.11.0"
|
||||||
framework: "net9.0"
|
framework: "net9.0"
|
||||||
overview: "Request movies and TV shows from a local admin review queue"
|
overview: "Request movies and TV shows from a local admin review queue"
|
||||||
|
|||||||
+5
-5
@@ -9,12 +9,12 @@
|
|||||||
"repositoryUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies",
|
"repositoryUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies",
|
||||||
"versions": [
|
"versions": [
|
||||||
{
|
{
|
||||||
"version": "1.0.0.2",
|
"version": "1.0.1.1",
|
||||||
"changelog": "Inject Request tab via File Transformation (Docker/Unraid safe); keep disk patch fallback",
|
"changelog": "Reduce Request tab flicker when returning home from collections",
|
||||||
"targetAbi": "10.11.11.0",
|
"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",
|
"sourceUrl": "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main/release/Jellyfin.Plugin.Request_1.0.1.1.zip",
|
||||||
"checksum": "DFD860D8E616B33B7BE31B3CEE462EAB",
|
"checksum": "EADA70C2BC7AAD32623E37FDBD85DF44",
|
||||||
"timestamp": "2026-08-02T20:41:46.8916597Z",
|
"timestamp": "2026-08-03T01:38:28.4011758Z",
|
||||||
"dependencies": []
|
"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.
@@ -1,5 +1,5 @@
|
|||||||
param(
|
param(
|
||||||
[string]$Version = "1.0.0.2",
|
[string]$Version = "1.0.1.1",
|
||||||
[string]$TargetAbi = "10.11.11.0",
|
[string]$TargetAbi = "10.11.11.0",
|
||||||
[string]$RepoRawBase = "https://git.masengr.com/Michael-A-Sloan/Jellyfin_Request_tvandmovies/raw/branch/main"
|
[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
|
$zipPath = Join-Path $releaseDir $zipFileName
|
||||||
$manifestPath = Join-Path $root "manifest.json"
|
$manifestPath = Join-Path $root "manifest.json"
|
||||||
$timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")
|
$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..."
|
Write-Host "Building plugin..."
|
||||||
dotnet build (Join-Path $root "Jellyfin.Plugin.Request.sln") -c Release
|
dotnet build (Join-Path $root "Jellyfin.Plugin.Request.sln") -c Release
|
||||||
|
|||||||
Reference in new issue
Block a user